Java ยท Chapter 32 of 42

Java Exceptions

An exception is an event that disrupts the normal flow of a program, such as dividing by zero or accessing an invalid array index. Java handles exceptions using try, catch, finally, and throw.

Exceptions are either checked (must be declared or caught, like IOException) or unchecked (RuntimeException subclasses, like NullPointerException), which don't require explicit handling.

Syntax
try {
} catch (Exception e) {
} finally {
}

try, catch, finally

Code that might throw an exception goes in a try block; catch blocks handle specific exception types; finally always runs, whether or not an exception occurred.

Checked vs unchecked

Checked exceptions must be declared with `throws` or handled; unchecked exceptions (RuntimeException and subclasses) do not require this.

Example 1 (java)
public class Main {
  public static void main(String[] args) {
    try {
      int result = 10 / 0;
    } catch (ArithmeticException e) {
      System.out.println("Error: " + e.getMessage());
    } finally {
      System.out.println("Done");
    }
  }
}
Output
Error: / by zero
Done

Dividing by zero throws an ArithmeticException, which is caught, then finally always runs.

Key points

  • try/catch handles exceptions gracefully.
  • finally always executes, error or not.
  • Checked exceptions must be declared or handled.
  • throw lets you raise your own exceptions.
๐Ÿ’ก Note: Avoid catching generic Exception unless necessary โ€” catch specific exception types when possible.

๐Ÿ“ Quick Quiz

1. What block always runs regardless of an exception?

2. What type of exception is ArithmeticException?

3. What keyword lets you raise your own exception?