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