Forgetting try-finally

Posted by Anders Mon, 25 Aug 2008 19:06:00 GMT

or “Hot Potato Exception Handling”

This is a common use of try-catch:

public void foo() { 
    // Catch any exception so that the call to super is done anyway 
    try { 
        //... 
    } catch (Exception e) { 
        // Log
        // ...
    } 
    // Call super last 
    super.foo(); 
}

You could think that the purpose of the try-catch is to enable logging of the exception. But the first comment (taken from actual example code) suggests that the logging is just incidental. The purpose is to make sure that something is run no matter what. The logging is just a case of not knowing anything better to do with the exception once it’s caught.

Instead, why not use the simple try-finally:

public void foo() { 
    try { 
        //... 
    } finally {
        super.foo(); 
    }
} 

We’re not “handling” the exception, but that’s probably good. We are handling non-Exception throwables though. I think people just forget that you can have a try-finally without the catch.

Posted in ,  | 1 comment

Comments

  1. anjan bacchu said about 1 hour later:
    hi there, I tend to forget once in a while. But there are many colleagues who don't know this construct at all. BR, ~A

Comments are disabled