Basic

Exception Handling

Catch and handle errors with try/catch/finally.

What you will see

try finally

About 2 min of reading

Try It

Catch errors instead of crashing. Wrap risky code in try, catch the matching exception, and run cleanup in finally, then watch execution continue after the catch.

1

Divide by two (safe this time) inside a try, catching ArithmeticException. The catch is there to show the shape of handling: only the matching exception is caught.

class Main { public static void main(String[] args) { try { int result = 10 / 2; System.out.println(result); } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } } }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
5
The catch only runs when a matching exception is actually thrown. Here division by two succeeds, so only 5 prints, try it with / 0 to see the message.
2

Parse a non-numeric string. The specific NumberFormatException is caught first, then the general Exception as a fallback. Order matters: specific before broad.

class Main { public static void main(String[] args) { try { int x = Integer.parseInt("abc"); System.out.println(x); } catch (NumberFormatException e) { System.out.println("Not a number"); } catch (Exception e) { System.out.println("Other error"); } } }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
Not a number
A broader catch cannot come before a more specific one, the compiler rejects it. Put specific exceptions first, Exception last.
3

The finally block always runs, whether or not an exception is thrown. Throw a RuntimeException inside try and watch finally still execute before the program reports the error.

class Main { public static void main(String[] args) { try { System.out.println("try"); throw new RuntimeException("boom"); } finally { System.out.println("finally"); } } }

Before you run it, say out loud what it will print. Then open the answer.

What it prints
try finally
finally runs for cleanup even though the uncaught exception later terminates the program. Use it for closing files or connections, which is why it always fires.

Data Flow

Code runs in a try block; on error control jumps to a matching catch, then always to finally.
1 try block starts running
↓
2 Exception raised -> normal flow breaks
↓
3 Matching catch handles it
↓
4 finally runs -> block exits
Why this works
When to catch

Use exceptions for exceptional conditions, not normal control flow. Catch what you can handle; let the rest bubble up. A common pattern is the resource-try-with-resources:

try (FileReader r = new FileReader("f.txt")) {
    // auto-closed
} catch (IOException e) {
    // handle
}

This guarantees resources close even if an exception occurs.

When you have a choice

Checked vs unchecked exceptions

TypeExampleEnforced
CheckedIOExceptionMust catch or declare
UncheckedNullPointerExceptionNot enforced

Checked exceptions (subclasses of Exception except RuntimeException) must be handled or declared with throws. Unchecked exceptions (subclasses of RuntimeException) are programming errors you should fix, not catch.

Examples

Catching exceptions

try/catch

try {
    int result = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
}

The catch block runs only if the matching exception is thrown. Execution continues after the block.

Multiple catch blocks

Specific handlers

try {
    int x = Integer.parseInt("abc");
} catch (NumberFormatException e) {
    System.out.println("Not a number");
} catch (Exception e) {
    System.out.println("Other error");
}

Order matters: catch specific exceptions before broader ones. The most general Exception must come last.

finally and throw

Cleanup and raising errors

try {
    openResource();
} finally {
    closeResource();   // always runs
}

static void check(int n) {
    if (n < 0) throw new IllegalArgumentException("Negative");
}

finally runs whether or not an exception occurred. throw explicitly raises an exception.

Words this lesson uses

Each one is defined here on this site. Open the entry for the full definition and the other words it points at.

← Methods and Functions
Previous Lesson
Methods and Functions
Next Lesson
Object-Oriented Programming
Object-Oriented Programming →