Menu
Topics Index
...
`


Exceptions >
Siva Nookala - 06 Oct 2016
Please note that finally keyword in exception handling is different from the final Keyword In Java. finally keyword is used in exception handling to include the code for releasing, closing or cleaning up of the resources.

As observed in the example Java Multiple Catch Block With Example Program, the close() method is called in multiple places in the try and catch blocks. To avoid this we can use the finally keyword and move the calling of close() method into the finally block.
ValuableResource vr = new ValuableResource();
try
{
    vr.initialize();
    vr.useTheResource();
    vr.useItInAnotherWay();
}
catch(ArithmeticException ae)
{
    System.out.println("Our apologies. We have some problems with calculations, our arithmetic support team is looking into it.");
}
catch(ArrayIndexOutOfBoundsException aioobe)
{
    System.out.println("Our apologies. We have some problems with accessing the data, please call support for further details.");
}
catch(NullPointerException npe)
{
    System.out.println("Our apologies. We have some internal errors.");
}
catch(Exception e)
{
    System.out.println("Our apologies. Unknown error occurred. We will get back to you shortly.");
}
finally
{
    // This block will be executed whether exception occurs or not
    vr.close();
}
The code in the finally block will get executed when exception does not occur or when it does occur. So any code placed in the finally block is definitely executed irrespective of what exception is thrown. Since we need to release the resources in all the situations, we can call the close method in the finally block.
Also note that it is valid to have try with out catch, but with a finally.
ValuableResource vr = new ValuableResource();
try
{
    vr.initialize();
    vr.useTheResource();
    vr.useItInAnotherWay();
}
finally
{
    vr.close();
}
When we do something like this, the exceptions are not handled and the user gets to see the raw messages from exceptions. But the resource will be closed properly even when the exception occurs, since we are calling the close() method in the finally block. Using try block with only finally will be useful when we have a common exception handling in the calling methods.

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App