Javascript: try / catch return statement

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

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

I expect the output of this function to be "true", but instead, "false"!

+49
javascript return try-catch
01 Oct '10 at 9:36
source share
6 answers

Finally, it is always satisfied. What this means, which means it is coming back, will be used in your case.

You will want to change your code to look like this:

 function example() { var returnState = false; // initialisation 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, which is why.

+49
01 Oct '10 at 9:45
source share

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

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

  • Let B be the result of block estimation.
  • Let F be the result of the Finally estimate.
  • If F.type is normal, return B.
  • Refund F.

And from page 36:

The termination type is used to explain the behavior of operators ( break , continue , return and throw ) that perform non-local control transfers. Values ​​of the type "Completion" are triples of the form (type, value, goal), where the type is one of normal , break , continue , return or throw , value is any ECMAScript value or empty, and the target is any ECMAScript identifier or empty.

It is clear that return false sets the completion type at the end to return, which will result in try ... finally 4. Return F.

+19
01 Oct 2018-10-10 at 10:56
source share

When you use finally , any code inside this block fires before the method exits. Since you are using return in the finally block, it calls return false and overrides the previous return true in the try block.

(The terminology may not be entirely correct.)

+5
01 Oct '10 at 9:42 on
source share

why you get false, you are back in the finally block. The finally block must always be executed. so your return true changes to return false

 function example() { try { return true; } catch { return false; } } 
+3
01 Oct '10 at 9:43 on
source share

As far as I know, the finally block is always executed, regardless of whether there is a return inside try or not. Ergo, you will get the value returned by the return inside the finally block.

I tested this with Firefox 3.6.10 and Chrome 6.0.472.63 as in Ubuntu. Perhaps this code may behave differently in other browsers.

0
Oct 01 '10 at 9:43 on
source share

Finally, it is assumed that ALWAYS starts at the end of the catch try block, so (by spec) is the reason you get false. Keep in mind that it’s possible that different browsers have different implementations.

-one
01 Oct '10 at 9:43 on
source share



All Articles