Table of contents
1.
Introduction
2.
Error object in javascript
3.
Exception handling Statements
3.1.
Try...catch statement.
3.2.
Throw statement
3.3.
Finally statement
4.
Frequently Asked Questions
4.1.
What are programming errors?
4.2.
What is meant by debugging?
4.3.
What are the exception handling statements in Javascript?
4.4.
Is the execution of the ‘finally’ statement dependent on the try-catch block?
5.
Conclusion
Last Updated: Dec 5, 2024
Easy

Handling Errors in Javascript

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

In the world of programming, errors can be called the twin brother of the code. No matter what code you are developing, you are bound to run into some sort of error at some point in time. Debugging is an essential part of coding. Just like any other programming language, the case is the same with Javascript. You will get errors. In this blog, we will look at how to do error handling in Javascript.

Also Read, Javascript hasOwnProperty

Error object in javascript

Before we look into the exception handling statements that Javascript offers, let us learn about the error object in Javascript.

Javascript has a built-in error object. This error object gives information about errors when one occurs. The error object has two parts- name and message. The name will return the name of the error. The function of the message is to return an error message. 

Example:

NameMessage
SyntaxErrorA syntax error has occurred

 

There are many other errors in Javascript. If you want to read about all of them, check this documentation.

Exception handling Statements

When we are talking about computers and programming, exception handling is the process of responding to the occurrence of exceptions in the code. These exceptional conditions or strange behaviour must be handled to ensure that the program or the piece of code runs smoothly.

When talking about error handling in javascript, some of the essential statements that come to light are:

  • Try...Catch statement
  • Throw statement
  • Finally statement

Try...catch statement.

The try statement in javascript lets us test a block of code for errors. The catch statement allows us to handle the error.

Syntax

try {
  Block of code to try
}
catch(err) {
  Block of code to handle errors
}

 

JS Code demonstrating the try-catch statement

<!DOCTYPE html>
<html>
  <body>
      <script>
        try {
          //here the alert() method is purposely misspelled as allert() to trigger the try-catch block
          allert("Welcome guest!");
        }
        catch(err) {
          //the try-catch block detects the error and catches it. The exception is stored in the 'err' object, which is then displayed on the screen.
        
          document.write(err);
        }
      </script>
  </body>
</html>

 

Output

ReferenceError: alert is not defined

 

In the above code, we purposefully misspell the alert() method as alert(). If we hadn’t put the wrong code in try-catch, we would not see any output. Javascript need not also print any error, and it can simply stop execution. However, by putting the wrong code in the try block, we tell Javascript that the following code set might have errors and should be looked for.

The catch block lets us handle the error. In this case, we have printed the error.

Throw statement

So far, we understand that when an error occurs in Javascript, the execution of the code might get interrupted. It is for this reason that we use exception handling mechanisms. Upon getting an error, Javascript will throw an exception, or we can say it will throw an exception.

The throw statement allows us to create custom errors. 

Syntax

throw expression; //Here expression can be string, object, boolean or number

 

JS code demonstrating the throw statement

In this code, we take the same example code from above and modify it.

<!DOCTYPE html>
<html>
   <body>
      <script>
         document.write("Voting Eligibility Checker</br>");
         const age = 17;
         document.write("Input age: "+age+"</br>");
         try {
             if(age >= 18) {
                 document.write('You can vote!');
             }
             else {
         
                 // user-defined throw statement
                 throw new Error('Age<18, you are not eligible to vote!');
             }
         
             // Since throw is being executed, the below statement will not be  printed
             document.write('This will not be printed');
         }
         catch(error) {
             document.write(error);  
         }
      </script>
   </body>
</html>

 

Output

Voting Eligibility Checker
Input age: 17
Error: Age<18, you are not eligible to vote!

 

Another example where the throw statement is not executed

<!DOCTYPE html>
<html>
   <body>
      <script>
         document.write("Voting Eligibility Checker</br>");
         const age = 35;
         document.write("Input age: "+age+"</br>");
         try {
             if(age >= 18) {
                 document.write('You can vote!'+"</br>");
             }
             else {
         
                 // user-defined throw statement
                 throw new Error('Age<18, you are not eligible to vote!');
             }
         
             
         // Since throw is not being executed, the below statement will be printed
         
             document.write('This will be printed, the throw is not executed.');
         }
         catch(error) {
             document.write(error);  
         }
      </script>
   </body>
</html>

 

Output

Voting Eligibility Checker
Input age: 35
You can vote!
This will be printed, the throw is not executed.

Finally statement

The ‘finally statement is given after the try and catch statements. The ‘finally’ block will execute the piece of code in it. It does not care about the result. It will always be executed.

Syntax

try {
  Block of code to try
}
catch(err) {
  Block of code to handle errors
}
finally {
  Block of code to be executed regardless of the try-catch result
}

 

JS Code demonstrating finally block

<!DOCTYPE html>
<html>
   <body>
      <script>
         document.write("Exam Score</br>");
         const score = 70;
         document.write("Input score: "+score+"</br>");
         try {
             if(score >= 50) {
                 document.write('Score is good.'+"</br>");
             }
             else {
         
                 // user-defined throw statement
                 throw new Error('The score is low, study well.');
             }
         
             // Since throw is not being executed, the below statement will be printed
             document.write('This will be printed, the throw is not executed.');
         }
         catch(error) {
             document.write(error);  
         }
         finally{
             //this will always be executed
          document.write("</br>"+'Reach out if you need any help.');
         }
      </script>
   </body>
</html>

 

Output

Exam Score
Input score: 70
The score is good.
This will be printed, the throw is not executed.
Reach out if you need help.


You can practice by yourself with the help of an online javascript compiler.

Must Read Fibonacci Series in JavaScript

Frequently Asked Questions

What are programming errors?

Errors are faults that occur in the program. These faults can make the program behaviour abnormal or unexpected.

What is meant by debugging?

Debugging is the process of removing errors or bugs from the program.

What are the exception handling statements in Javascript?

The exception handling statements in Javascript are try, catch, finally and throw.

Is the execution of the ‘finally’ statement dependent on the try-catch block?

No. The ‘finally’ statement is given after the try-catch block, but the codes enclosed under finally will always execute irrespective of the results of the try-catch block.

Conclusion

Errors are bound to come up while developing something. Errors are faults that occur in the program. These faults can make the program behaviour abnormal or unexpected. A good programmer must learn to identify these errors and find ways to solve them. This process of finding errors and resolving them is called debugging. Debugging is one cool skill you need to have with you. The exception handling statements in Javascript helps in handling errors.

Live masterclass