Reputation: 970
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?
Upvotes: 3
Views: 4120
Reputation: 1499900
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.
Upvotes: 6
Reputation: 214949
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.
Upvotes: 3
Reputation:
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;
}
Upvotes: 1