views:

125

answers:

4

What exactly does a finally block in exception handling perform?

+3  A: 

It executes no matter if you get into the catch block or not, meaning that is a great place for disposing of objects and doing other cleanups.

klausbyskov
+6  A: 

It holds code that should always be executed, regardless of whether an exception occurs.

For example, if you have opened a file, you should close it in the finally block to ensure that it will always be closed; if you closed it in the try block, an earlier exception would cause execution to jump straight to the catch block and skip closing the file.

See the Java tutorials for more details.

Michael Myers
+4  A: 

The finally block always executes, regardless of whether or not the exception was thrown. The classic use example I can think of is closing files.

FileOutputStream stream = null;
try{
    // do stuff with the stream here
} catch (IOException ex){
    // handle exception
} finally{
    // always close the stream
    if(stream != null){
        stream.close();
    }
}
TwentyMiles
I just realized that this won't actually work because stream.close() itself throws an exception! Yet another reason why I dislike Java exceptions. The example should still show the general use pattern however, so I'll leave it up.
TwentyMiles
A better way of arranging the code is: `acquire(); try { use(); } finally { release(); }`.
Tom Hawtin - tackline
+2  A: 

I use it a lot for cleaning up open resources when there are multiple return statements in a block of code, making the code a lot cleaner as you don't need to clone the same 'close resource' code before every return statement. It's guaranteed that the code will call the finally section, even if you do a return within the try section. It also helps with code safety in this instance, since the programmer could easily leave it out by accident.

Chris Dennett