Advanced Topics

Java Exception Handling

Learn how to handle errors gracefully in Java using try-catch-finally, custom exceptions, and best practices.

What are Exceptions?

Exceptions are runtime errors that disrupt normal program flow. Java's exception handling lets you catch and handle these errors gracefully instead of crashing.

java
// Without exception handling — program crashes
int result = 10 / 0;  // ArithmeticException!

// With exception handling — program continues
try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero!");
}

Try-Catch-Finally

java
try {
    // Code that might throw an exception
    int[] arr = {1, 2, 3};
    System.out.println(arr[5]);
} catch (ArrayIndexOutOfBoundsException e) {
    // Handle the exception
    System.out.println("Invalid index: " + e.getMessage());
} finally {
    // Always executes (cleanup code)
    System.out.println("This always runs.");
}

Exception Hierarchy

Throwable
├── Error (serious — don't catch)
│   ├── OutOfMemoryError
│   └── StackOverflowError
└── Exception
    ├── IOException (checked)
    ├── SQLException (checked)
    └── RuntimeException (unchecked)
        ├── NullPointerException
        ├── ArithmeticException
        ├── ArrayIndexOutOfBoundsException
        └── NumberFormatException
TypeMust Handle?Examples
Checked✓ Yes (compile-time)IOException, SQLException
Unchecked✗ No (runtime)NullPointerException, ArithmeticException

Multiple Catch Blocks

java
try {
    String str = null;
    System.out.println(str.length());
} catch (NullPointerException e) {
    System.out.println("Null reference: " + e.getMessage());
} catch (Exception e) {
    System.out.println("General error: " + e.getMessage());
}

Throw and Throws

java
// throw — manually throw an exception
public static void validateAge(int age) {
    if (age < 0) {
        throw new IllegalArgumentException("Age cannot be negative: " + age);
    }
}

// throws — declare that a method might throw
public static void readFile(String path) throws IOException {
    FileReader reader = new FileReader(path);
    // ...
}

Custom Exceptions

java
public class InsufficientBalanceException extends Exception {
    private double balance;
    private double amount;

    public InsufficientBalanceException(double balance, double amount) {
        super(String.format("Cannot withdraw ₹%.2f. Balance: ₹%.2f", amount, balance));
        this.balance = balance;
        this.amount = amount;
    }
}

Try-With-Resources

Automatically closes resources:

java
try (Scanner scanner = new Scanner(new File("data.txt"))) {
    while (scanner.hasNextLine()) {
        System.out.println(scanner.nextLine());
    }
} catch (FileNotFoundException e) {
    System.out.println("File not found: " + e.getMessage());
}
// Scanner is automatically closed here

Practical Example

java
import java.util.Scanner;

public class SafeDivision {
    public static double divide(int a, int b) throws ArithmeticException {
        if (b == 0) throw new ArithmeticException("Division by zero");
        return (double) a / b;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        try {
            System.out.print("Enter numerator: ");
            int a = Integer.parseInt(scanner.nextLine());

            System.out.print("Enter denominator: ");
            int b = Integer.parseInt(scanner.nextLine());

            double result = divide(a, b);
            System.out.printf("Result: %.2f%n", result);
        } catch (NumberFormatException e) {
            System.out.println("Please enter valid numbers.");
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        } finally {
            scanner.close();
            System.out.println("Calculator closed.");
        }
    }
}

Summary

  • Exceptions are runtime errors; Java handles them with try-catch-finally
  • Checked exceptions must be handled or declared; unchecked are optional
  • Use throw to manually throw exceptions; throws to declare them
  • Create custom exceptions by extending Exception or RuntimeException
  • Try-with-resources automatically closes AutoCloseable resources
  • finally block always executes — ideal for cleanup code