Handling Exceptions in JavaScript

Introduction

 
As we know an exception is an error that occurs during execution caused by an incorrect operation when a program is syntactically correct. 
 
Example: When you try to reference an undefined variable or call a non-existent method, an exception will occur. The statements that you want to monitor for exceptions are contained within a try block. If an exception occurs within the try block then it is thrown. You can catch this thrown exception using the catch block that handles the exceptions.
 
The following are the main two ways in JavaScript to handle exceptions:
  • Using the try-catch statement
  • Using the onerror event
Let's explain both.
 
The try-catch Statement: In JavaScript, you need to write code that can generate an error in the try block. Immediately after the try block, there is a catch block that specifies the exception type that you want to catch. The syntax of the try-catch statement is as follows:
  1. Try  
  2. {  
  3.    // code that can cause an error  
  4. }  
  5. Catch(err)  
  6. {  
  7.    // What to do when an error occurs  
In the preceding syntax, there are two blocks: try and catch. The try block contains the suspected code that can generate the errors. If the error occurs then the try block throws an exception that is caught by each block. There is another optional block known as a finally block that is associated with the try-catch statement. The syntax of the finally block is as follows.
  1. Try  
  2. {  
  3. // code that can use an error  
  4. }  
  5. catch (err)  
  6. {  
  7. // what to do when an error occurs  
  8. }  
  9. Finally  
  10. }  
  11. // code that executes in all cases  
The optional finally block of the try-catch statement always runs its code whether or not an exception are thrown. If the code in the try block runs completely then the finally block executes. If there is an error then the catch block executes, and then the finally block executes. Any time control is about to return to the caller from inside a try or catch block through an explicit return statement, the finally block executes just before the control returns.
 
The onerror Event: Any error that is not handled by the try-catch statement causes the onerror event to fire on the window object. The onerror event does not create an event object ; it is called by the object of the window that has the errors. It accepts the following three arguments:
  • The error message
  • The uniform resource location (URL) of the web page on which the error occurred
  • The line number that contains the error
When the onerror event triggers, it displays the error message, the URL of the web page, and the line number at which the error occurs. The syntax is given below:
  1. window.onerror = function (ermessage, url, line) {  
  2. alert(message);  
Here, we used the window object to call the onerror event that takes the following three arguments:
  • Error Message
  • URL
  • The Line Number
Let's Work with an Example
First we will do the example:
  • Using the onerror event
As we explained above, when the onerror event triggers, it displays the:
  • Error message
  • URL of the Web Page
  • Line Number
The following is the code
 
JavaScript Code
 
The code above shows how to handle exceptions by using the onerror event.
 
Here n is a variable that is undefined and we are trying to print the value of the n variable at line 11 that generates the error that n is undefined. When the error occurs the onerror is triggered and displays the error message, URL and the line number.
 
Output
 
The following is the output
 
JavaScript onerror Event
 

Using a try-catch statement

 
We know that a try block contains the suspected code that can generate errors. If the error occurs then the try block throws an exception that is caught by the catch block. The following is the code:
 
JavaScript Try Catch Statement
 
The code above has two blocks, try and catch.
 
In the try block, we are trying to print the undefined variable n. So this block throws an exception that is caught by the catch block. Then the catch block displays the type of the exception by using the err object.
 
Note that in the try block, there is one more write() function containing the C# Corner string that is never executed because once an exception is thrown the program transfers the control from the try block to the catch block.
 
Output
 
JavaScript Try Catch Statement Output
 
But we explained above that there is another optional block, the finally block. 
 
The finally block of a try-catch statement always runs its code whether or not execution is thrown.
 
The following is the code:
 
JavaScript with Finally
 
The code above has three blocks.
 
The try block generates the undefined variable exception that is caught by the catch block. Then the finally block executes and displays the C# Corner string, even when the exception has occurred. See the following output:
 
Exception Output