Card 01/ 10

ConceptDifficulty: Beginner1 min

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:

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

The three parts, and when each one runs
BlockRuns
tryUntil it finishes or something throws
catchOnly if something threw, and only for a matching type
finallyAlways, 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.