166

How does a return statement inside a try/catch block work?

function example() {
    try {
        return true;
    }
    finally {
        return false;
    }
}

I'm expecting the output of this function to be true, but instead it is false!

2
  • 2
    For others, do the return false in the catch block, not finally. Mar 17, 2020 at 15:33
  • 1
    Use finally not for logic but for clean-up, eg to free resources. A return statement is not appropriate for use in finally. Jun 1, 2022 at 7:48

10 Answers 10

152

Finally always executes. That's what it's for, which means its return value gets used in your case.

You'll want to change your code so it's more like this:

function example() { 
    var returnState = false; // initialization value is really up to the design
    try { 
        returnState = true; 
    } 
    catch {
        returnState = false;
    }
    finally { 
        return returnState; 
    } 
} 

Generally speaking you never want to have more than one return statement in a function, things like this are why.

8
  • 95
    I would argue having more than one return statement isn't always bad - See stackoverflow.com/questions/36707/… for more discussion. Oct 1, 2010 at 9:52
  • 12
    I too disagree about the one return rule. You should never return from finally, though (in C#, it's not even allowed).
    – erikkallen
    Oct 1, 2010 at 10:58
  • 1
    @Castrohenge - it's not a hard and fast rule, but most of the copunter-examples in that thread are pretty contrived, and the only valid case I see is the "guard clause" (essentially the pattern of checking input data at the top of the function and returning conditionally). That's a perfectly valid case, but really those returns should be exceptions (again not hard and fast).
    – annakata
    Oct 1, 2010 at 12:12
  • 1
    Actually in IE6 and IE7, finally doesn't always execute in all cases due to a pretty serious browser bug. Specifically – if an exception is thrown in a try-finally block that isn't surrounded by a higher level try-catch, then the finally block won't execute. Here's a test case jsfiddle.net/niallsmart/aFjKq. This issue was fixed in IE8. Jun 17, 2011 at 20:46
  • 2
    To always have at most one return statement per function is a misinterpreted historical advice and is generally agreed to be wrong. Mar 10, 2020 at 22:52
69

According to ECMA-262 (5ed, December 2009), in pp. 96:

The production TryStatement : try Block Finally is evaluated as follows:

  1. Let B be the result of evaluating Block.
  2. Let F be the result of evaluating Finally.
  3. If F.type is normal, return B.
  4. Return F.

And from pp. 36:

The Completion type is used to explain the behaviour of statements (break, continue, return and throw) that perform nonlocal transfers of control. Values of the Completion type are triples of the form (type, value, target), where type is one of normal, break, continue, return, or throw, value is any ECMAScript language value or empty, and target is any ECMAScript identifier or empty.

It's clear that return false would set completion type of finally as return, which cause try ... finally to do 4. Return F.

1
  • 6
    After reading all sorts of "basically correct but somehow squishy and non-clarifying" answers to this question, this one actually made it make sense. The key bit was that whatever "happens" at the end of the try+catch (return or throw or just normal flow) is remembered while it runs the finally part and then actually happens only if nothing happens at the end of finally. Mar 6, 2020 at 18:36
24

When you use finally, any code within that block fires before the method exits. Because you're using a return in the finally block, it calls return false and overrides the previous return true in the try block.

(Terminology might not be quite right.)

12

The finally block rewrites try block return (figuratively speaking).

Just wanted to point out, that if you return something from finally, then it will be returned from the function. But if in finally there is no 'return' word - it will be returned the value from try block;

function example() {
    try {
        return true;
    }
    finally {
       console.log('finally')
    }
}
console.log(example());
// -> finally
// -> true

So -finally- return rewrites the return of -try- return.

8

I'm gonna give a slightly different answer here: Yes, both the try and finally block get executed, and finally takes precedence over the actual "return" value for a function. However, these return values aren't always used in your code.

Here's why:

  • The example below will use res.send() from Express.js, which creates a HTTP response and dispatches it.
  • Your try and finally block will both execute this function like so:
try {
    // Get DB records etc.
    return res.send('try');
} catch(e) {
    // log errors
} finally {
    return res.send('finally');
}

This code will show the string try in your browser. ALSO, the example will show an error in your console. The res.send() function is called twice. This will happen with anything that is a function. The try-catch-finally block will obfuscate this fact to the untrained eye, because (personally) I only associate return values with function-scopes.

Imho your best bet is to never use return inside a finally block. It will overcomplicate your code and potentially mask errors.

In fact, there's a default code inspection rule set-up in PHPStorm that gives a "Warning" for this:

https://www.jetbrains.com/help/phpstorm/javascript-and-typescript-return-inside-finally-block.html

So what do you use finally for?

I would use finally only to clean-up stuff. Anything that is not critical for the return value of a function.

It may make sense if you think about it, because when you depend on a line of code under finally, you are assuming that there could be errors in try or catch. But those last 2 are the actual building blocks of error handling. Just use a return in try and catch instead.

1
  • Strongly agree with this answer - would only add that if your running into issues with the return behavior, just put the return outside the finally block! It always runs there unless you return in the try/catch! I think it would be better to have another language construct for finally outside the try/catch behavior because of this oddity though, something like do {/*stuff*/} always {/*clean up*/) Aug 7, 2021 at 17:30
3

why you are getting false is you returned in a finally block. finally block should execute always. so your return true changes to return false

function example() {
    try {
        return true;
    }
    catch {
        return false;
    }
}
2

Returning from a finally-block

If the finally-block returns a value, this value becomes the return value of the entire try-catch-finally statement, regardless of any return statements in the try and catch-blocks

Reference: developer.mozilla.org

1

As far as I know, the finally block always executes, irrespective of whether you have a return statement inside try or not. Ergo, you get the value returned by the return statement inside finally block.

I tested this with Firefox 3.6.10 and Chrome 6.0.472.63 both in Ubuntu. It is possible that this code may behave differently in other browsers.

0

The only thing you should remember in try/catch/finally is that the 'The last return always wins'. You can not skip the finally block with the return statement inside try or catch block. It will always be executed at the end. There is a nice post about that. Hope it can help you to understand better.

0
-2

Finally is supposed to ALWAYS run at the end of a try catch block so that (by specification) is why you are getting false returned. Keep in mind that it is entirely possible that different browsers have different implementations.

1
  • IE8, Firefox 3.6 and Chrome 6: all the same ;)
    – bonfo
    Oct 1, 2010 at 9:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.