JavaScript

Error Handling in JavaScript

Error handling in JavaScript is a method that is utilized to handle the encountered error and maintain the flow of your JavaScript code. It also permits the execution of abnormal statements that exists within a program.

JavaScript offers various errors handlers that process the encountered error and execute the code that is added for handling the error. For instance, when you divide any non-zero value by zero, it will yield infinity. This is an error that is handled by the JavaScript exception handling procedure.

This write-up will discuss Error Handling in JavaScript. Moreover, the procedure of using try-catch block, throw statement, and the try-catch-finally blocks, their syntax, and examples related to error handling are also provided.

Before moving towards the error handling procedure, let’s check out the type of JavaScript errors.

Types of Errors in JavaScript

There exist three types of errors that might occur while executing a JavaScript program:

  • Logical Error: Logical error is a type of error which encounter when your program contains any logical error that terminates it abnormally and does not provide the desired output.
  • Runtime Error: A Runtime error encounters during the execution of your JavaScript code. Error handlers are then utilized to handle the Runtime error.
  • Syntax Error: A syntax error occurs when you make any kind of mistake in the JavaScript pre-defined syntax.

Error Handling Statements in JavaScript

If any error occurs, the following statements blocks are used to handle it in JavaScript:

  • try block: In JavaScript coding, the “try” block comprises the code that can throw an error.
  • catch block: To handle the encountered error, you have to write out the code in the “catch” block. These kinds of statements are mainly used for displaying customized messages or to log errors.
  • finally block: Regardless of whether an error occurs or not, the final block code will always get executed. It can be utilized for resetting variables that are changed because of the try block. You can also use the “finally” block for completing the remaining tasks of your JavaScript program.

Error Handling in JavaScript using try-catch block

In the JavaScript programming language, a try-catch block is used for handling the code that is prone to error. The try-catch block firstly checks the program if there exist any errors. Then, if any error occurs, it takes the specified action to handle it. A good JavaScript programming approach is to keep complex code within the try-catch block.

Now, check out the below-given flowchart to understand the working of the “try-catch” block in JavaScript:

Blank diagram

Syntax of try-catch block

To use a try-catch block in JavaScript, you have to follow the below-given syntax:

try{  
//try code block }
catch(error){  
//catch code block }

The code which is added in the “try” block will be executed first. If any error encounters, the “catch” code block will be run next, otherwise, it will be ignored.

Example: Using try-catch block for handling error in JavaScript

First of all, we will define an array “x” in our try block and then we will call the “document.write(x)” method for displaying the “x” array elements. Next, the added “document.write(a)” lines will invoke the catch block, as we have not defined variable “a” in our code and we are trying to fetch its value. In this case, the catch-block will handle the encountered error by displaying its related information in the alert box:

<html>

<head> Exception Handling in JavaScript</head>

<body>

<script>

try{

var x= ["10","12","6","25"];

document.write(x);

document.write(a);

}catch(e){

alert("The encountered error is "+e.message);

}

</script>

</body>

</html>

The execution of this JavaScript program will display the elements of the “x” array while showing an alert for the encountered error “a is not defined”:

Error Handling in JavaScript using throw statement

You can also use the “throw” statement for defining custom errors. When the JavaScript interpreter will execute the throw statement, it will shift the control towards the catch block and will not run any code present after the “throw” statement.

Syntax of throw statement

Now, check out the syntax of using throw statement in the try-catch block

try{

//try code block

throw Exception;

}

catch(error){

//catch code block }

Here, “Exception” is added to define custom exceptions which can be a number, string, or any boolean value.

Example: Using throw statement for Error Handling in JavaScript

In this example, we will use the throw statement for creating a custom “a throw keyword” error:

<html>

<head>Exception Handling in JavaScript</head>

<body>

<script>

try {
  thrownewError('a throw keyword');
}
catch (e) {
  document.write(e.message);  
}


</script>

</body>

</html>

The execution of the above-given code will show you the following output:

Error Handling in JavaScript using try-catch-finally block

In your JavaScript code, once the try and catch statements are executed, the optional “finally” block runs after that. Whether the exception is thrown or not, the “finally” block code will run

Syntax of try-catch-finally block

Have a look at the syntax of the try-catch-finally block:

try{

//try code block

}

catch(error){

//catch code block

}

finally{

//finally code block }

Here, the “try” code block checks for the errors, then the “catch” block will be executed to handle the encountered error, and lastly, the “finally” code block contains the executable code which will always run, regardless of any error that occurs or not.

Example: Using try-catch-finally block for Error Handling in JavaScript

In the following example, we will define a try-catch-block. In the first step, first of all, we have defined a variable “x”in the try block. After that, the try block will check if the added value for the “x” variable matched with the value specified in the “if” condition. It will print out the “okay” string when the “if” condition is true. In the other case, the added “catch” block will be executed. Lastly, the code written in the “finally” block will display the string “value of x is 10” as output:

<html>

<head>Exception Handling in JavaScript</head>

<body>

<script>

try{

var x=10;

if(x==10)

document.write("okay ");

}

catch(Error){

document.write("Error found "+e.message);

}

finally{

document.write("Value of x is 10 ");

}

</script>

</body>

</html>

As you can see from the output, the code written in the “try” and “finally” block is executed for the added logic in our JavaScript program:

Error Objects in JavaScript

In JavaScript, the “Error Object” is a type of built-in object that provides information related to the encountered error. It comprises two useful properties: “name” and “message”. The “name” property of the error object is utilized to set or return the error name, whereas the “message” sets or returns the error message which can be a string.

Error Name Values in JavaScript

The error name property can return the following values in the JavaScript:

Eval Error: This type of error name value indicates that an error occurred in the “eval()” function.

Range Error: If you use a number in your JavaScript code that is outside of the range of the legal values, a “RangeError” is thrown.

Reference Error: If you refer to a variable that has not been declared anywhere in your program, a “ReferenceError” is thrown.

Syntax Error: Syntax Error indicates that you are trying to execute code having syntax error.

Type Error: If you utilize a value that is outside of the expected data types, then a “TypeError” is thrown.

URI Error: The use of illegal characters in a URI function can be the reason behind the URI Error.

Conclusion

For handling errors in JavaScript, the procedure of using try-catch block, throw statement, and the try-catch-finally blocks are well explained along with their syntax, and related examples in this write-up. According to your requirements, you can use any of the given statements to handle the encountered error, maintain the flow of your JavaScript program, and ease the code development process in JavaScript.

About the author

Sharqa Hameed

I am a Linux enthusiast, I love to read Every Linux blog on the internet. I hold masters degree in computer science and am passionate about learning and teaching.