Can syntax errors be caught in JavaScript?

It's runtime errors that can be caught with try-catch, not syntax errors (if you eval your code you can handle syntax errors in the evaled code but that's just weird).

I'd recommend you read these:

  • https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Statements#try...catch_Statement

  • https://developer.mozilla.org/en/Core_JavaScript_1.5_Guide/Statements#Exception_Handling_Statements


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:

<script>
  window.onerror = function (e) {
    console.log('Error: ', e);
  };
  console.log('a'');
</script>

This will work:

<script>
  window.onerror = function (e) {
    console.log('Error: ', e);
  };
</script>
<script>
  console.log('a'');
</script>

jsfiddle demo

Tags:

Javascript