Question

In MDN its stated,

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

So I try to execute the following code,

function an(){
    var r = try{
        throw 1;
    } catch(e){
        console.log("Caught: %o", e);
    } finally {
        return 2;
    }
    console.log("r=%o", r);
    return 3;
}

It does not work. Throws a syntax error.

SyntaxError: syntax error

    var r = try{

Whats wrong here?

Was it helpful?

Solution

I think the problem is simply that you're trying to assign a try statement to a variable. As far as I'm aware (and I'm no JS expert) you can't do that. It's a statement, not an expression.

I believe this is entirely separate to what happens with return values.

Try putting your try/catch/finally statement into a separate function, and call that instead, assigning the result to r:

function foo() {
    try {
        throw 1;
    } catch(e) {
        console.log("Caught: %o", e);
    } finally {
        return 2;
    }
}

var r = foo();
console.log("r=%o", r);

In Chrome's Javascript console, that gives:

Caught: 1
r=2

EDIT: I agree that the term "production" in the docs is a bit confusing here. According to comments, it's technically accurate - but that doesn't stop it from being confusing, of course. I suspect that in most cases "function" would be clearer, probably less definitively accurate.

OTHER TIPS

Your assumption is wrong. You have syntax error. try block dont returns anything.

function an(){
var r;// <---- here
try{// <----- here
    throw 1;
} catch(e){
    console.log("Caught: %o", e);
} finally {
    return 2;
}
console.log("r=%o", r);
return 3;
}

What they mean is this:

function an() {
    try {
        throw 999;
        return "in try";
    } catch(e) {
        return "in catch";
    } finally {
        return "in finally";
    }
    return "in func";
}

console.log(an()) // in finally

JS ignores all return statements, except the one in the finally block.

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