Reputation: 89633
Kangax blog has a code example: §
try {
(var x = 5); // grouping operator can only contain expression, not a statement (which `var` is)
} catch(err) {
// SyntaxError
}
Since the syntax error at line 2 would affect the "syntax of the entire code", what's the point of the catch
statement here?
Is catch
able to catch syntax errors in JavaScript?
Upvotes: 1
Views: 214
Reputation: 5253
You are right, javascript parser will generate an error, so it will never catch it.
Maybe his intention was to point out the wrong syntax (grouping operator can only contain expression, not a statement), but the try / catch statement is useless.
Moreover, the comment //syntaxError
inside catch let suppose that the catch will do something.
Upvotes: 2
Reputation: 61727
Syntax errors wont be caught by try/catch, as you can't wrap variable assignments in brackets like that.
Upvotes: 1
Reputation: 700352
No, that is correct. Using a try...catch
doesn't help against syntax errors.
The script block won't run at all if there is a syntax error keeping it from being parsed.
Upvotes: 1