Signup/Sign In

JavaScript Error Handling - try, catch, finally and onerror Event

An Exception is an error that occurs at the time of execution(runtime) due to an illegal operation when a program is syntactically correct. For example, whenever you try to reference an undefined variable or call a non-existent method; an exception will occur.

We have already covered JavaScript Error and in this tutorial we will cover how we can handle error and runtime excption in our JavaScript code to avoid abrupt end of code execution.

So Exception or Error handling begins by identifying the code which we think may give some error/exception when we run it. Such code blocks can be enclosed within a special try block which is a special code block in which if any runtime exception occurs, then we can handle that exception in the catch block.

The statements that you want to monitor for an exception are contained within a try block. If an exception occurs within the try block then it is thrown.

You can catch this thrown exception by using the catch block that handles the exception.

Ways to Handle Errors/Exceptions in JavaScript:

There are mainly two ways to handle exceptions in JavaScript:

1. Using try, catch and finally statement

2. Using the onerror event

Let us discuss the above given ways to handle exception one by one.

JavaScript try and catch Statement

In JavaScript, you must write such code, which, if generates an error/exception at runtime, is inside the try block, so that the exception/error can be handled gracefully. Immediately, after the try block, there should be a catch block that specifies the exception type you want to catch.

In simple words, the code statements which we want to execute, are kept inside the try block, followed by a catch block. This informs JavaScript to try and execute the given code statements and if any exception occurs, throw it, and the catch block will catch the exception, and then the code inside the catch block is executed.

JavaScript try and catch Syntax:

Let's see the syntax for the try and catch blocks:

    // code that can cause an error
    // what to do when an error occurs

In the above syntax, there are two blocks try and catch. Where the try block contains the suspected code that can generate errors. If an error occurs then try block throws the exception that is caught by the catch block, in which we can handle it as we want. We can either show a user readable message or we can show the error message in an alert box.

JavaScript try and catch Example:

Let's take an example to see JavaScript try and catch block in action:

In the above code, we have created a Web page that shows how to handle an exception using try-catch statement. It contains two code blocks - try and catch.

In the try block, we are trying to print the value of undefined variable n, Therefore, the try block throws an exception that is caught by the catch block. Then the catch block displays the message stored in the Error object using the err reference.

Note that in the try block, there is one more document.write() function call containing the Hello World! string , which is never executed because once an exception is thrown, the program transfer the control from try block to the catch block.

JavaScript finally Statement

We also have an optional statement called as the finally statement that is associated with the try and catch statement. It is used to execute some code after the try and catch code blocks are executed. JavaScript finally statement makes sure that the code statements inside the finally block are executed, no matter what.

JavaScript finally Statement: Syntax

The finally statement is used after the try and catch statements,

    // code that can cause an error
    // what to do when an error occurs
    //code that execute in all the cases

The optional finally block of try-catch statement always runs its code whether or not an exception is thrown. There may be two cases:

  • If the code in the try block runs successfully without any exception, then catch block will not get executed but the finally block will be executed.

  • If there is an error in the try block, then the catch block executes, after that finally block executes

Anytime a control is about to return to the caller method from inside a try or catch block through an explicit return statement, the finally block is executed just before the control returns.

In short, no matter what happens, if you have defined a finally block, it will be executed.

JavaScript try, catch and finally Example:

Here we have another example of handling runtime exception in JavaScript code and using the finally statement.

In the above code, we have created a web page that shows how the finally block works. The above code contains three blocks: try, catch and finally. The try block generates an undefined variable exception that is caught by the catch block. Then the finally block executes and displays the Hello world string, even when the exception has occurred.

JavaScript onerror Event to Handle Exception

Any error that is not handled by 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 window that has errors.

It accepts three arguments:

  1. The error message

  2. The Uniform Resource Locator(URL) of the page on which error has occurred

  3. The line number that contains the error.

When the onerror event triggers, it displays the error message. The URL of the web page, the line number at which error occurs.

JavaScript onerror Event Syntax:

Following is the syntax for using the onerror event:

window.onerror = function(errmessage, url, line)

In the above code, we used the window object to call the onerror event and we can specify an event handler function for it.

JavaScript onerror Event Example:

In this example, we are handling error using onerror event:

Well, with this we have reached the end of JavaScript Exception handling tutorial. In this tutorial we learned about the try, catch and finally statements which are used for handling runtime exception in JavaScript code and we covered one more way of handling exception which is using the onerror event.

About the author:
I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development. Founder @ Studytonight