Can syntax errors be caught in JavaScript?

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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)