-2
  1. I got "Uncaught SyntaxError: Invalid or unexpected token" error.
  2. And try to catch with 'try ~ catch' but it's not working.

    function a(){
      try{
       var img1 = "=="";  <#-- it occurs error -->
      }catch (e) {
        console.log("image error:" + e.message);
      }
    }
    
11
  • 6
    Is that your exact code? Also you can't catch syntax errors (outside of eval at least). Commented Jun 26, 2018 at 7:55
  • I occurs error Intentionally to test catch statement. But it can't catch the error. Commented Jun 26, 2018 at 7:58
  • 1
    AFAIK syntax error is not exception Commented Jun 26, 2018 at 7:59
  • Syntax errors are checked at the parsing time, try .. catch is executed at the running time, which will never take place because a syntax error has interrupted the script. Commented Jun 26, 2018 at 7:59
  • 2
    Possible duplicate of Can syntax errors be caught in JavaScript? Commented Jun 26, 2018 at 8:13

1 Answer 1

5

You have a syntax error and you can not catch a syntax error.

This error is checked at the parsing or validation time of your code. The try .. catch statement is executed at the running time. And because of this it was not functioning.

If you eval or parse (for ex. JSON) your code you can handle syntax errors only. Or you can create a syntax error like this:

try {
  throw new SyntaxError('Hello', 'someFile.js', 18);
} catch (e) {

  console.log(e.message);  // "Hello"
  console.log(e.name);  // "SyntaxError"
}

For the eval handled or by self created syntax errors:

A SyntaxError is thrown when the JavaScript engine encounters tokens or token order that does not conform to the syntax of the language when parsing code.

From MDN

Try this:

    function a(){
      try{
       var img1 = "==\"";
       //but you have to put some error here without parsing or validation error of your code.
      }catch (e) {
        console.log("image error:" + e.message);
      }
    }

I would like to recommend you read:

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

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.