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