How to catch syntax errors in JavaScript?

JavascriptWeb DevelopmentFront End Technology

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.

raja
Published on 23-Feb-2018 06:57:32
Advertisements