Pebellslearn by building
0%
RoadmapsMatrixCoursesSandboxSign in
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.

try, catch and finally

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).

The shortcut

To predict the output, trace with your finger and jump at the throw. Run the try line by line; at the throwing line, jump to the first matching catch; then always visit finally. If nothing throws, skip the catches and still visit finally.

Tracing typed = "two"Step 1 of 4
  1. Enter try

    Integer.parseInt("two") cannot read a number, so it throws a NumberFormatException.

Drills

Answer fast — trust the rule.

quick drill

What does this print? try { System.out.print("A"); Integer.parseInt("two"); System.out.print("B"); } catch (NumberFormatException e) { System.out.print("C"); } finally { System.out.print("D"); }

quick drill

The same code, but parsing "2" instead. What prints?

quick drill

Why does a catch (Exception e) placed above catch (NumberFormatException e) fail to compile?

quick drill

When does a finally block run?

Remember

  • Try the risky part, catch what you can fix, finally tidy up.
  • Trace with your finger: jump at the throw, first matching catch, then finally.
  • Traps: general catches above specific ones, and code after the throw that you expect to run.

Practice — level up

0/1 solved

Write your answer, then compare it with a rubric and a model answer.

ExplainKeep the till running

The till reads a cup count typed by the barista with Integer.parseInt, and must always switch the keypad light off afterwards. Explain how you would structure this with try, catch and finally, what happens step by step when the barista types 'abc', and what changes when they type '3'.