Java · Module 7 · Lesson 11 min read

try, catch & finally

What is an exception?

An exception is an event that interrupts normal flow, like dividing by zero, reading a missing file, or calling a method on null.

The exception family tree

scss
Throwable
├── Error            → serious JVM problems (OutOfMemoryError). Don't catch.
└── Exception
    ├── RuntimeException → UNCHECKED (bugs in your code)
    │     NullPointerException, ArithmeticException,
    │     ArrayIndexOutOfBoundsException, IllegalArgumentException
    └── others           → CHECKED (outside problems)
          IOException, SQLException
  • Checked exceptions must be handled with try/catch or declared with throws. The compiler forces you.
  • Unchecked exceptions usually mean a bug. Fix the code rather than catching them everywhere.

try / catch / finally

Java
try {
    int result = 10 / divisor;
} catch (ArithmeticException e) {
    System.out.println("Can't divide by zero!");
} finally {
    System.out.println("Always runs");   // cleanup code
}
  • Put specific catches before general ones (Exception last).
  • Catch several at once: catch (IOException | SQLException e).
  • finally runs whether or not an exception happened (it's skipped only if the JVM stops, e.g. System.exit).

throw vs throws

  • throw → creates an exception: throw new IllegalArgumentException("Age can't be negative");
  • throws → warns callers a method might throw: void readFile() throws IOException

Useful methods on an exception

e.getMessage() gives the message. e.printStackTrace() shows where it happened, which is great for debugging.

Example

Java
public class SafeDivide {
    static int divide(int a, int b) {
        if (b == 0) throw new ArithmeticException("Divider is zero");
        return a / b;
    }

    public static void main(String[] args) {
        try {
            System.out.println(divide(10, 2));  // 5
            System.out.println(divide(5, 0));   // throws
            System.out.println("Never printed");
        } catch (ArithmeticException e) {
            System.out.println("Oops: " + e.getMessage());
        } finally {
            System.out.println("Done ✅");
        }
    }
}
// 5
// Oops: Divider is zero
// Done ✅