Java – Does it make sense to do “try-finally” without “catch”

exceptionjava

I saw some code like this:

    try
    {
        db.store(mydata);
    }
    finally
    {
        db.cleanup();
    }

I thought try is supposed to have a catch?

Why does this code do it this way?

Best Answer

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