JavaScript Try...Catch Statement


There are two ways of catching errors in a web page:
  • by using the try...catch statement or
  • by using the onerror event.
 <html><body>
  <script type="text/javascript">
   try {
     // Run some code here
   }
   catch( err ) {
     // Handle errors here
   }
  </script>
 </body></html>

The try...catch statement allows you to test a block of code for errors. The try block contains the code to be run, and the catch block contains the code to be executed if an error occurs. Note that try...catch is written in lowercase letters. Using uppercase letters will generate a JavaScript error!

The example tries to display the message “Welcome guest!” by using the try...catch statement. Since alert is misspelled, a JavaScript error occurs.



   

The exception argument is a variable in which to store the error, in this case it is the variable err. It will be discussed in the next slide. The onClick event executes JavaScript code when a click event occurs; that is, when an object on a form is clicked.


Demonstration
The following demonstration shows how the script of HTML and JavaScript is displayed on the Web.

     





      Did you hear what happened when the guy who    
      wrote the song ‘The Hokey Pokey’ died?    
      They couldn’t close his coffin.    
      Every time they put a right foot in, he put his left foot out.    
      — Felipe Esparza