Exception Handling in Java

Site Admin · 11 Sep 2026 · 11 views

Dealing With the Unexpected

An exception is an event that interrupts the normal flow of a program - like reading a file that was deleted or dividing by zero. Rather than letting the program crash, Java lets you catch the problem and respond.

The try-catch Block

try {
    int[] numbers = {1, 2, 3};
    System.out.println(numbers[10]);   // triggers an exception
    System.out.println("This line never runs");
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Invalid index used!");
}

If an exception occurs inside try, control jumps straight to the matching catch, and the program continues.

Multiple Catches

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
} catch (Exception e) {
    System.out.println("Something else went wrong: " + e.getMessage());
}

Order matters: catch the most specific exception first (ArithmeticException before Exception).

finally

The finally block always runs whether or not an exception occurred, which makes it ideal for cleanup.

try {
    int n = 100 / 0;
} finally {
    System.out.println("Cleanup always runs");
}

throw vs throws

  • throw raises an exception you create.
  • throws on the method signature declares that the method may raise one, telling callers to handle it.
static double sqrtSafe(double x) throws IllegalArgumentException {
    if (x < 0) throw new IllegalArgumentException("Negative input");
    return Math.sqrt(x);
}

Custom Exceptions

class InsufficientFundsException extends Exception {
    InsufficientFundsException(String message) { super(message); }
}

void withdraw(double amount) throws InsufficientFundsException {
    if (amount > balance) {
        throw new InsufficientFundsException("Not enough money");
    }
    balance -= amount;
}

Checked vs Unchecked

  • Checked exceptions (IOException, SQLException etc.) must be handled or declared.
  • Unchecked exceptions (NullPointerException, ArithmeticException) extend RuntimeException and are not required to be declared.

try-with-resources

Automatically closes resources that implement AutoCloseable:

try (Scanner sc = new Scanner(System.in)) {
    System.out.println(sc.nextInt());
} // sc is closed automatically

Exception handling

Exception hierarchy

Key Points

  • Use try-catch to handle and recover from runtime problems.
  • finally guarantees cleanup; try-with-resources is cleaner for resources.
  • Create custom exceptions to describe your domain's failure cases.
Share this post:

Comments (0)

Please login or register to comment.