Alex Rivera | Logout

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

Asked 2010-04-10T18:37:36.187
175

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?

Edit
Report

1 Answer

250

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();
    }
}
answered 2010-04-10T18:39:35.607

Your Answer