Search code examples
javatry-catch-finallythrowable

Using finally without a catch


I have a test I want to execute. No matter if it passes or throws an error I want to close a case it opened. I have at the top of the class String theCase = null; Then in executeText() I set it once the case is open.

So I did this :

try {
    executeTest(tContext);
} catch (Throwable t) {
    throw t;
} finally {
    if (theCase != null) {
      closeCase(user, theCase);
    }
}

I am wondering. Do I need the catch (Throwable t)? I still want the error to be thrown, but first I want it to close the case. If I don't catch it and throw it, will finally not throw it? Or will it not be caught and throw the exception and not execute the finally? I am a bit unclear about finally.


Solution

  • Do I need the catch (Throwable t)?

    No you don't.

    In fact, it is harmful, because if you catch and throw Throwable like that, then for some versions of Java you will need to declare the enclosing method as throws Throwable ... and so on. (That was address in Java 8, IIRC.)