Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can syntax errors be caught in JavaScript?

Tags:

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?

like image 233
Pacerier Avatar asked May 11 '11 10:05

Pacerier


People also ask

What is syntax error in JavaScript?

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.

Is there a try catch in JavaScript?

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.

What kind of error occurs in JavaScript?

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.

What happens when JavaScript throws an error?

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.


1 Answers

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

like image 171
rohithpr Avatar answered Sep 29 '22 11:09

rohithpr