Can syntax errors be detected in JavaScript?

MDN status :

Syntax An error is raised when the JavaScript engine detects tokens or tokens that do not match the language syntax when parsing the code.

But if there is a syntax error, how can a program work in the first place?

How can JavaScript syntax errors be detected?

+5
source share
5 answers

These are runtime errors that can be caught using try-catch, not syntax errors ( if you are evalyour code , you can handle syntax errors in evaled code, but this is just weird).

I would recommend you read them:

+5

, , JavaScript,, window.onerror.

JavaScript- The Complete Reference by Thomas-Powell, . .

+4

try-catch , , .

window.onerror , . , onerror script, , !

:

, script :

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

:

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

jsfiddle demo

+4

, JavaScript, JSLint JSHint .

  • . .
  • JavaScript.
  • ???
  • Profit!
0

JS SyntaxError CAN . , , JSON, JSON-. , , , JSON , SyntaxError, JS. , : SyntaxError: JSON Parse error: Unrecognized token '<'.

, . Mozilla : Errors JSON

You may want to catch them in your code. You can do this with a generic try / catch block as follows:

try {
  JSON.parse('<html></html>');
} catch (e) {
  console.log("I catch & handle all errors the same way.");
}

OR you can search for SyntaxError:

try {
  JSON.parse('<html></html>');
} catch (e) {
  if (e instanceof SyntaxError) {
    console.log("I caught a pesky SyntaxError! I'll handle it specifically here.");
  } else {
    console.log("I caught an error, but it wasn't a SyntaxError. I handle all non-SyntaxErrors here.");
  }
}

Mozilla has even more information about JS errors and how to handle them .

0
source

All Articles