Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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

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

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.

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top