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:
tryholds 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.finallyruns 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.
Enter try
Integer.parseInt("two")cannot read a number, so it throws a NumberFormatException.
Drills
Answer fast — trust the rule.
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"); }
The same code, but parsing "2" instead. What prints?
Why does a catch (Exception e) placed above catch (NumberFormatException e) fail to compile?
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.
