1

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?

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Certain engines may treat syntax errors as runtime errors and vice versa. For example, if (false) { new Object = 1; } is treated as a syntax error in Firefox even though the specs permit this.
@user123444555621, It's a syntax error (and thus uncatchable) in Chrome too. Are you sure the specs permit this? Which specs?
1

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.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.