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.
The try... catch statement is comprised of a try block and either a catch block, a finally block, or both. The code in the try block is executed first, and if it throws an exception, the code in the catch block will be executed.
A finally block always executes, regardless of whether an exception is thrown. The following code example uses a try / catch block to catch an ArgumentOutOfRangeException.
The purpose of a finally block is to ensure that code gets run in three circumstances which would not very cleanly be handled using "catch" blocks alone: If code within the try block exits via return.
The try statement defines the code block to run (to try). The catch statement defines a code block to handle any error. The finally statement defines a code block to run regardless of the result. The throw statement defines a custom error.
They are the same. I would use the second version.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With