Pacerier
Pacerier

Reputation: 89633

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?

Upvotes: 1

Views: 214

Answers (3)

Manuel Bitto
Manuel Bitto

Reputation: 5253

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.

Upvotes: 2

Tom Gullen
Tom Gullen

Reputation: 61727

Syntax errors wont be caught by try/catch, as you can't wrap variable assignments in brackets like that.

Upvotes: 1

Guffa
Guffa

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

Related Questions