Can syntax errors be caught in JavaScript?

前端 未结 5 1249
说谎
说谎 2020-12-06 09:38

MDN states:

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

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-06 10:31

    You cannot use try-catch blocks to handle syntax errors as they are thrown while the code is being parsed and not while it's running.

    However you can use window.onerror and figure out that there's an error. You must ensure that the onerror function is defined in a separate script tag and not in the tag in which the error may be present!

    Eg:

    This will not work, because the script is yet to start running when the error is thrown:

    
    

    This will work:

    
    
    

    jsfiddle demo

提交回复
热议问题