Dan Burton
Dan Burton

Reputation: 53675

Is this `try..catch..finally` redundant?

public Foo doDangerousStuff() throws Exception {
    try {
        dangerousMethod();
        return new Foo();
    } catch (Exception e) {
        throw e;
    } finally {
        mustBeCalledAfterDangerousMethod();
    }
}

Does this behave any differently than if we were to omit the catch clause?

public Foo doDangerousStuff() throws Exception {
    try {
        dangerousMethod();
        return new Foo();
    } finally {
        mustBeCalledAfterDangerousMethod();
    }
}

[edit] To clear the confusion, yes, the catch block does nothing except re-throw the exception. I was wondering if this caused some sort of different ordering in when the finally block is invoked (assume that the thrown exception is caught by the caller), but from what I infer from the answers thusfar, it does not.

Upvotes: 11

Views: 807

Answers (5)

Nathan Ryan
Nathan Ryan

Reputation: 13041

Though the two source codes represent the same execution sequence, they will result in different bytecode. The first routine will have an exception table, for example, whereas the second will not. Their bytecode will have the same effect during execution, in the absence of instrumentation. It is possible that these methods behave differently if the bytecode is instrumented after compilation, or if the caught exception is of a type whose classfile is not available during execution.

Upvotes: 3

fmucar
fmucar

Reputation: 14558

As you are throwing the exception you have caught in the catch clause and doing nothing else but throwing it again, yes both code will do the same thing.

Upvotes: 2

Kal
Kal

Reputation: 24910

Yes. Since your method already throws "Exception", you dont need to catch it and re-throw it. Unless you want do what @Dave mentioned.

Upvotes: 5

Michael Barker
Michael Barker

Reputation: 14378

They are the same. I would use the second version.

Upvotes: 7

Jan Zyka
Jan Zyka

Reputation: 17888

You are right, it is the same. Even the stacktrace will be there :)

But similar code might be use if you wrap the exception into some higher level one. If the code looks exactly like stated it is really pointless.

Upvotes: 1

Related Questions