Does it make sense to do "try-finally" without "catch"?

It's there because the programmer wanted to make sure that db.cleanup() is called even if the code inside the try block throws an exception. Any exceptions will not be handled by that block, but they'll only be propagated upwards after the finally block is executed. The finally block will also be executed if there was no exception.


Why does this code do it this way?

Because apparently the code doesn’t know how to handle exceptions at this level. That’s fine – as long as one of the callers does, i.e. as long as the exception gets ultimately handled somewhere.

Often, low-level code cannot react appropriately to exceptions because the user needs to be notified, or the exception must be logged, or another strategy has to be tried. Low-level code performs one function only and doesn’t know about higher-level decision making.

But the code still needs to clean up its resources (because if it doesn’t, they would leak), so it does just that in the finally clause, making sure that it always happens, whether an exception was thrown or not.


This is useful if you want the currently executing method to still throw the exception while allowing resources to be cleaned up appropriately. Below is a concrete example of handling the exception from a calling method.

public void yourOtherMethod() {
    try {
        yourMethod();
    } catch (YourException ex) {
        // handle exception
    }
}    

public void yourMethod() throws YourException {
    try {
        db.store(mydata);
    } finally {
        db.cleanup();
    }
}

The finally block ensures that even when a RuntimeException is thrown (maybe due to some bug in the called code), the db.cleanup() call will be made.

This is also often used to prevent too much nesting:

try
{
    if (foo) return false;
    //bla ...
    return true;
}
finally
{
    //clean up
}

Especially when there are many points at which the method returns, this improves readability as anyone can see the clean up code is called in every case.

Tags:

Java

Exception