Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
If you try to cook something, you start by turning on the oven.
If the thing you try is a complete failure, you have to turn off the oven.
If the thing you try succeeds, you have to turn off the oven.
You have to turn off the oven no matter what!
A finally block is where you put code that must run regardless of an exception.
try { turnOvenOn(); x.bake(); } catch (BakingException ex) { ex.printStackTrace(); } finally { turnOvenOff(); }
Without finally, you have to put the turnOvenOff() in both the try and the catch because you have to turn off the oven no matter what. A finally block lets you put all your important cleanup code in one place instead of duplicating it like this: