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(); 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(); 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.
|