Card 01/ 10
Java Exceptions: try, catch and finally
A report half written when the disk fills, and the caller three calls away who knows what to do.
An exception is an object a method throws to say it cannot complete its work. The method stops at once, and Java hands the exception up through its callers until one of them has a catch block for that type. Code in a finally block runs whichever way the try ends.
A method is halfway through writing a report when the disk fills. It cannot finish, and it cannot decide what should happen instead: the method that asked for the report knows that, and it is three calls away. The exception carries the decision up to it:
try {
writeReport(path);
System.out.println("written");
} catch (IOException e) {
System.out.println("could not write: " + e.getMessage());
}If writeReport throws, line 3 never runs. Control jumps straight to the matching catch, which is the only place execution resumes.
| Block | Runs |
|---|---|
try | Until it finishes or something throws |
catch | Only if something threw, and only for a matching type |
finally | Always, whichever of the two happened |
The catch names the type of exception it handles, here IOException, and receives the exception object as e. e.getMessage() gives the text the thrower attached, which is usually the first thing worth logging or showing.
A finally block is where cleanup goes, such as closing a file the try opened, because it runs whether the report was written or the disk filled halfway through.
So an exception is a return path that skips every line between the failure and the handler. That is exactly what makes it useful, since no method in between has to check a return code, and exactly what makes swallowing one so expensive.
← → move through sections and cards