Handling Errors

JavaScript uses the try...catch statement to deal with errors.

 
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<body>
  <script type="text/javascript">
    try {
      var myArray;
      for ( var i = 0; i < myArray.length; i++) {
        document.writeln("Index " + i + ": " + myArray[i]);
      }
    } catch (e) {
      document.writeln("Error: " + e);
    }
  </script>
</body>
</html>
  
Click to view the demo

The properties defined by the Error object:

PropertyDescriptionReturns
messageA description of the error condition.string
nameThe name of the error. This is Error, by default.string
numberThe error number, if any, for this kind of error.number

The optional finally clause is executed regardless of the error.

 
<!DOCTYPE HTML>
<html>
<head>
<title>Example</title>
</head>
<body>
  <script type="text/javascript">
    try {
      var myArray;
      for ( var i = 0; i < myArray.length; i++) {
        document.writeln("Index " + i + ": " + myArray[i]);
      }
    } catch (e) {
      document.writeln("Error: " + e);
    } finally {
      document.writeln("Statements here are always executed");
    }
  </script>
</body>
</html>
  
Click to view the demo