Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

11. Exception Handling: Risky Behavior > Finally: for the things you want to do...

Finally: for the things you want to do no matter what

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:


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial