Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 431
Dan Burton Avatar asked May 04 '11 20:05

Dan Burton


People also ask

Can I use try catch finally?

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.

Is finally in try catch always 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.

What's the point of finally in try catch?

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.

What is the difference between try catch and finally keywords?

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.


1 Answers

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

like image 105
Michael Barker Avatar answered Sep 23 '22 04:09

Michael Barker