Pacerier Pacerier - 7 months ago 10
Javascript Question

Can catch statement catch syntax errors in JavaScript?

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?

Answer

You are right, javascript parser will generate an error, so it will never catch it.

http://jsbin.com/oluje5/edit

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.

Comments