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 when parsing code.
But if there's a syntax error, how could the program even run in the first place?
How can JavaScript syntax errors even be caught?
An exception caused by the incorrect use of a pre-defined syntax. Syntax errors are detected while compiling or parsing source code. For example, if you leave off a closing brace ( } ) when defining a JavaScript function, you trigger a syntax error.
JavaScript try and catchThe try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
Errors are statements that don't let the program run properly. There are three main types of errors that can occur while compiling a JavaScript program: syntax errors, runtime errors, and logical errors.
The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With