JavaScript - SPLessons

JavaScript Error Handling

Chapter 27

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

JavaScript Error Handling

JavaScript Error Handling

shape Introduction

When running a JavaScript program, different errors may occur. Errors can be categorized into different types such as coding errors made by the programmer, errors due to wrong input, and other unpredictable errors. The present chapter explains about JavaScript Error Handling.

Basically, there are three types of errors in JavaScript, they are:


Run-time Errors

shape Introduction

Run-time errors are called as exceptions and occur due to various reasons. For example, referring a method which is not defined is an exception. In JavaScript, the exceptions are handled through try/catch/finally blocks.

try

JavaScript statements that are likely to cause exceptions has to be wrapped in a try block. If any exception persists in the try block, the control goes to catch block or finally block or sometimes both. So there are three forms for try statement.

catch

In catch block, the exception object is passed by skipping the rest of try statements. The exceptions in catch block has different properties like description, message, and stack trace.

finally

The block finally() executes even if the exception won’t occur. It will freeup the resources holding by script during the program execution. This can be used to close a file when any exception occurs during processing.

shape Syntax

Syntax for try and catch block is as follows.
try
{
// protected code
}
catch( Exceptiontype e )
{
// alternative statements
}

Syntax for finally block is as follows.


finally {
// Code that is always executed regardless of
// an exception occurring
}

shape Example

Below is an example for try and catch blocks.

<!DOCTYPE html>
<html>
<head>
	<title>Error Handling</title>
</head>
<body>
<script>
try
{
    // Referencing a function that does not exist cause an exception
    document.write(test());
    // Since the above line causes an exception, the following line will not be executed
    document.write("This line will not be executed");
}
// When an exception occurs, the control is transferred to the catch block
catch (e)
{
    document.write("Description = " + e.description + "<br/>");
    document.write("Message = " + e.message + "<br/>");
    document.write("Stack = " + e.stack + "<br/><br/>");
}

document.write("This line will be executed");
</script>
</body>
</html>

Output:

Below is an example for Try, Catch and Finally blocks.

<!DOCTYPE html>
<html>
   
   <head>
      
      <script type="text/javascript">
        
            function myFunction()
            {
               var a = 100;
               
               try {
                  alert("Value of variable a is : " + a );
               }
               
               catch ( e ) {
                  alert("Error: " + e.description );
               }
               
               finally {
                  alert("Finally block executes always!" );
               }
            }
       
      </script>
      
   </head>
   
   <body>
      <p>Click the following to see the result:</p>
      
      <form>
         <input type="button" value="Click Me" onclick="myFunction();" />
      </form>
      
   </body>
</html>

Output: When the button is clicked for the first time, try block gets executed and the following result will appear.

When clicked on OK in alert message, the finally block gets executed as there are no errors in try block.

Syntax Errors

shape Description

Syntax errors cannot handle the events with try/catch/finally blocks. These errors are called as parsing errors and occur at compile time. Only some part of the program gets effected with this error. For example,

<script type="text/javascript">
   <!--
      window.printme();
   //-->
</script>

Syntax Errors

shape Description

Logical Errors are very typical to handle as they depend on the requirements of a unit. These errors occur neither at run-time nor compile-time. You will get unexpected results when logical errors occur.

Summary

shape Key Points

JavaScript Error Handling chapter draws out the following important points.

  • Try, Catch and Finally blocks are used to handle the run-time errors.
  • Finally block executes even if the exception does not occur.
  • Syntax errors occur at compile-time.