Skip to the workspace
Pebellslearn by building
Exception Handling  ›  Lesson

try, catch and finally

Exception Handling 14 minCode that may fail goes in a try block, the first catch block whose type matches the thrown exception handles it, and finally runs in every case.

java / try, catch and finally

Explore each scene at your own pace.

01 · The rule

The rule

try, catch and finally

Code that may fail goes in a try block, the first catch block whose type matches the thrown exception handles it, and finally runs in every case.

Follow normal, exceptional and cleanup paths through the same operation.

A barista types "two" instead of 2 into the cup-count box, and the whole till program crashes in the middle of the lunch rush. Mistakes like that will always happen. Exception handling lets the program notice the problem, respond sensibly, and keep going.

The rule

Try the risky part, catch what you can fix, finally tidy up.

When something goes wrong at run time, Java creates an exception object and throws it. Normal execution stops at that line, and the exception travels back up through the calling methods until something catches it. If nothing does, the program ends with a stack trace.

String typed = "two";
try {
    int cups = Integer.parseInt(typed);   // throws here
    System.out.println("Cups: " + cups);  // skipped
} catch (NumberFormatException e) {
    System.out.println("Please type a number, like 2");
} finally {
    System.out.println("Order screen ready");
}

The three parts:

  • try holds the code that might fail. At the first throw, the rest of the try block is skipped.
  • catch (Type e) runs only if the thrown exception is that type or a subtype of it. e.getMessage() describes what went wrong. You can have several catch blocks; Java uses the first one that matches, from the top.
  • finally runs whether or not anything was thrown, even if the try block returns early. It is the place for clean-up.

Because the first matching catch wins, put specific types above general ones. Exception catches almost everything, so a catch for NumberFormatException below it could never run, and the compiler rejects it.

If one response fits several types, a multi-catch lists them with a vertical bar, as in catch (NumberFormatException | ArithmeticException e).

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.