Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Notes › Java

Exception Handling in Java

An exception is an event that breaks the normal flow of a program — dividing by zero, a missing file, a null reference. Handling it lets the program recover or fail with a clear message instead of crashing.

Hierarchy

Throwable
├── Error                      (serious, don't catch: OutOfMemoryError, StackOverflowError)
└── Exception
    ├── IOException, SQLException, ...         ← checked
    └── RuntimeException                        ← unchecked
        ├── NullPointerException
        ├── ArithmeticException
        ├── ArrayIndexOutOfBoundsException
        ├── IllegalArgumentException
        └── NumberFormatException

Checked vs unchecked

Checked Unchecked
Extends Exception (not Runtime) RuntimeException
Checked by the compiler nobody — happens at run time
You must catch it or declare throws nothing (but you can catch it)
Usually means something outside your control (file, network) a bug in the code
Examples IOException, SQLException NullPointerException, ArithmeticException

try / catch / finally

try {
    int[] a = new int[3];
    a[5] = 10;                                   // throws
    System.out.println("not printed");
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Bad index: " + e.getMessage());
} catch (Exception e) {                          // more general catch goes LAST
    System.out.println("Something else");
} finally {
    System.out.println("always runs");           // cleanup
}

throw vs throws

void withdraw(double amount) throws InsufficientFundsException {   // throws: declares it
    if (amount > balance)
        throw new InsufficientFundsException("Balance is only " + balance);   // throw: raises it
    balance -= amount;
}
throw throws
inside a method body in the method signature
throws one exception object lists exception types the method may throw

Custom exceptions

class InsufficientFundsException extends Exception {        // checked
    public InsufficientFundsException(String msg) { super(msg); }
}

Extend RuntimeException instead for an unchecked one.

try-with-resources (Java 7+)

Anything that implements AutoCloseable is closed automatically, even when an exception happens.

try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
    String line;
    while ((line = br.readLine()) != null) System.out.println(line);
} catch (IOException e) {
    e.printStackTrace();
}                                                // br.close() called for you

Exception propagation

An unhandled exception moves up the call stack — method → its caller → … → main. If nobody catches it, the thread ends and the stack trace is printed.

Best practices

Interview one-liners

More Java notes