Forgetting try-finally

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.

This entry was posted in Java, Programming. Bookmark the permalink.

One Response to Forgetting try-finally

  1. anjan bacchu says:

    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 closed.