Tony
Tony

Reputation: 1155

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.

Upvotes: 1

Views: 65

Answers (2)

Stephen C
Stephen C

Reputation: 718798

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

Upvotes: 2

bashrc
bashrc

Reputation: 4835

Finally will be executed irrespective of whether an exception was thrown or not, or whether it was rethrown from a catch block.

Upvotes: 1

Related Questions