Java Reference
In-Depth Information
The finally Keyword
The finally keyword is used to create a block of code that follows a try block. A
finally block of code always executes, whether or not an exception has occurred.
Using a finally block allows you to run any cleanup-type statements that you
want to execute, no matter what happens in the protected code. A finally block
appears at the end of the catch blocks and has the following syntax:
try
{
//Protected code
}catch( ExceptionType1 e1)
{
//Catch block
}catch( ExceptionType2 e2)
{
//Catch block
}catch( ExceptionType3 e3)
{
//Catch block
}finally
{
//The finally block always executes.
}
You can even write a try block that does not have any corresponding catch
blocks, only a finally block:
try
{
//Protected code
}finally
{
//The finally block always executes.
}
Why use a finally block? Well, you may want to close a file that has been
opened, even if your program could not read from the file for some reason. In
other words, if a read is successful, you want to close the file, and if the read
fails, you still want to close the file. A finally block can be used to simplify the
way this code will look.
try
{
//Try to read from a file.
}catch(IOException e)
{
Search WWH ::




Custom Search