Computer >> Computer tutorials >  >> Programming >> Javascript

How to catch syntax errors in JavaScript?


You cannot use try-catch blocks for handling syntax errors in JavaScript since it is thrown while the code is being parsed.

Example

Use window.onerror as in the following code −

<html>
   <head>
      <script>
         window.onerror = function(e) {
            document.write('Error: ', e, '</br>')
         };
      </script>
     
      <script>
         document.write('x'x')
      </script>
   </head>
 
   <body>
   </body>
</html>

Note − Ensure that the error function is defined in a separate <script> tag.