Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

finally in exception handling

What exactly does a finally block in exception handling perform?

like image 269
abson Avatar asked Mar 24 '10 16:03

abson


2 Answers

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.

like image 157
Michael Myers Avatar answered Sep 21 '22 03:09

Michael Myers


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();
    }
}
like image 22
TwentyMiles Avatar answered Sep 20 '22 03:09

TwentyMiles