Java Exception Handling

Error handling mechanisms using try-catch blocks, checked and unchecked exceptions

java (1.0+) 2025-11-03 exceptions error-handling try-catch

Description

Java’s exception handling mechanism allows programs to handle errors gracefully. Exceptions are objects that represent exceptional conditions and can be caught and handled using try-catch blocks.

Exception Types

  • Checked exceptions: Must be declared or caught (e.g., IOException)
  • Unchecked exceptions: Runtime exceptions (e.g., NullPointerException)
  • Errors: Serious problems (e.g., OutOfMemoryError)

Exception Handling

  • try-catch: Catch and handle exceptions
  • finally: Code that always executes
  • try-with-resources: Automatic resource management
  • throws: Declare exceptions that may be thrown
  • throw: Explicitly throw an exception

Code

RAW
import java.io.*;public class ExceptionHandling {        // Basic try-catch    public static void basicTryCatch() {        try {            int result = 10 / 0;        } catch (ArithmeticException e) {            System.out.println("Division by zero: " + e.getMessage());        }    }        // Multiple catch blocks    public static void multipleCatch() {        try {            // Some code        } catch (NullPointerException e) {            System.out.println("Null pointer: " + e.getMessage());        } catch (IllegalArgumentException e) {            System.out.println("Illegal argument: " + e.getMessage());        } catch (Exception e) {            System.out.println("General exception: " + e.getMessage());        }    }        // Try-catch-finally    public static void tryFinally() {        try {            // Code that might throw exception        } catch (Exception e) {            // Handle exception        } finally {            // Always executed            System.out.println("Cleanup code");        }    }        // Try-with-resources    public static void tryWithResources() throws IOException {        try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {            String line = reader.readLine();            // Resource automatically closed        }    }        // Custom exception    public static class CustomException extends Exception {        public CustomException(String message) {            super(message);        }    }        // Throwing exceptions    public static void throwException() throws CustomException {        throw new CustomException("Something went wrong");    }        // Exception propagation    public static void propagateException() throws IOException {        // Method declares it may throw IOException    }}
RAW
// Basic exception handlingtry {    int[] numbers = {1, 2, 3};    int value = numbers[5]; // ArrayIndexOutOfBoundsException} catch (ArrayIndexOutOfBoundsException e) {    System.out.println("Index out of bounds: " + e.getMessage());}// Handling multiple exceptionstry {    String str = null;    int length = str.length(); // NullPointerException} catch (NullPointerException e) {    System.out.println("Null pointer exception");} catch (Exception e) {    System.out.println("General exception: " + e.getMessage());}// Finally blocktry {    // Risky operation} catch (Exception e) {    // Handle exception} finally {    // Always executed for cleanup    System.out.println("Cleanup");}// Try-with-resources (auto-closes)try (FileInputStream fis = new FileInputStream("file.txt")) {    // Read from file} catch (IOException e) {    System.out.println("IO error: " + e.getMessage());}// FileInputStream automatically closed// Catching and rethrowingtry {    riskyOperation();} catch (Exception e) {    System.err.println("Error occurred: " + e.getMessage());    throw new RuntimeException("Wrapped exception", e);}// Checked exception handlingpublic void readFile() {    try {        FileReader reader = new FileReader("file.txt");        // Use reader    } catch (FileNotFoundException e) {        System.out.println("File not found: " + e.getMessage());    } catch (IOException e) {        System.out.println("IO error: " + e.getMessage());    }}

Comments

No comments yet. Be the first to comment!