Table of contents
1.
Introduction
2.
What is Exception Handling?
3.
Syntax Error
3.1.
Example
4.
ReferenceError
4.1.
Example
5.
TypeError
5.1.
Example
6.
RangeError
6.1.
Example
7.
Logical Error
7.1.
Example
8.
Runtime Error
8.1.
Example
9.
Error Object
9.1.
Example
10.
Frequently Asked Questions
10.1.
What is the difference between a syntax error and a logical error in JavaScript?
10.2.
How can I handle runtime errors in JavaScript?
10.3.
What is the Error object in JavaScript?
11.
Conclusion
Last Updated: Dec 20, 2024
Easy

Exception Handling in JavaScript

Author Sinki Kumari
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Exception handling in JavaScript allows developers to manage errors in their code effectively. It involves using constructs like try, catch, finally, and throw to detect and handle runtime errors. By capturing exceptions, developers can provide solutions, display meaningful error messages, and prevent abrupt program termination. Effective exception handling improves code reliability and debugging, making applications more user-friendly and robust. 

Exception Handling in JavaScript

In this article, we will discuss different types of errors, how to handle them, and provide examples of exception handling in JavaScript. 

What is Exception Handling?

In JavaScript, exception handling is the method of managing runtime errors in a structured manner. Instead of allowing an error to crash the application, exception handling captures the error and addresses it effectively. This approach ensures the program continues to run smoothly without disruption.

The primary method for managing errors in JavaScript involves using try, catch, and finally blocks.

Syntax Error

syntax error occurs when the JavaScript engine encounters code that doesn’t follow the language's rules. These errors are usually detected before the code is executed.

Example

let x = 10
console.log(x)
You can also try this code with Online Javascript Compiler
Run Code


In the above code, there is a syntax error because we forgot to add a semicolon after let x = 10. JavaScript expects a semicolon to terminate the statement properly. If we run the code without fixing the error, it will throw an error message like this:

Uncaught SyntaxError: missing ; before statement

 

A syntax error is easy to fix because it’s detected during the compilation phase, before the code even runs.

ReferenceError

A ReferenceError is thrown when you try to access a variable or function that has not been defined.

Example

console.log(x); // ReferenceError: x is not defined

TypeError

A TypeError occurs when you perform an operation on a value that is not of the expected type.

Example

let num = 10;
num.toUpperCase(); // TypeError: num.toUpperCase is not a function

RangeError

This error is thrown when a value is not within the allowed range. For example, attempting to create an array with a negative length.

Example

let arr = new Array(-1); // RangeError: Invalid array length

Logical Error

A logical error occurs when the code executes without syntax problems, but the result or behavior deviates from what the programmer intended. These errors can be challenging to identify since the program runs successfully but produces incorrect or unexpected outcomes.

Example

let num1 = 10;
let num2 = 20;
let result = num1 + num2;  // Expected output: 30
console.log("The product is: " + result);
You can also try this code with Online Javascript Compiler
Run Code


Here, the expected result was the product of num1 and num2, but instead, we added them. The correct code should be:

let result = num1 * num2;  // This will give the correct product.


In this case, the logical error led to an incorrect output, but there was no syntax issue, and the program still executed.

Runtime Error

A runtime error occurs when an issue arises while the program is being executed. These errors are more difficult to identify because they do not appear during the coding or compilation process but only manifest when the code is run.

Example

let arr = [1, 2, 3];
console.log(arr[5]);  // Attempting to access an index that does not exist
You can also try this code with Online Javascript Compiler
Run Code


In this code, trying to access arr[5] results in an undefined value, which is a runtime error because the index doesn't exist in the array. However, it won't stop the program from running unless it’s specifically handled.

To catch and handle this runtime error, we can use exception handling:

try {
  let arr = [1, 2, 3];
  console.log(arr[5]);
} catch (error) {
  console.log("Error occurred: " + error.message);
}
You can also try this code with Online Javascript Compiler
Run Code


Output:

Error occurred: Cannot read properties of undefined (reading '5')


Here, we used the try block to run the code and the catch block to handle the error by displaying a friendly message.

Error Object

JavaScript provides an Error object to help us deal with errors. This object contains useful information about the error, such as its name, message, and stack trace.

Example

try {
  let a = 10;
  let b = 0;
  if (b === 0) {
    throw new Error("Division by zero is not allowed");
  }
  console.log(a / b);
} catch (error) {
  console.log("Caught an error: " + error.message);
}
You can also try this code with Online Javascript Compiler
Run Code


In this code, the throw statement is used to create a custom error when dividing by zero. The catch block catches the error and prints the message from the Error object.


Output:

Caught an error: Division by zero is not allowed


The Error object provides additional properties like stack, which gives more detailed information about the error’s location in the code.

Frequently Asked Questions

What is the difference between a syntax error and a logical error in JavaScript?

A syntax error arises when the code breaks JavaScript's language rules, preventing it from executing. In contrast, a logical error occurs when the code executes successfully but produces incorrect or unexpected results.

How can I handle runtime errors in JavaScript?

Runtime errors can be handled using try, catch, and finally blocks. The catch block helps to capture the error and display a custom error message without stopping the program.

What is the Error object in JavaScript?

The Error object is a built-in object in JavaScript that contains information about an error, such as its name, message, and stack trace. You can use it to throw custom errors and handle them effectively.

Conclusion

In this article, we discussed the various types of errors in JavaScript, including syntax, logical, and runtime errors. It explained how to manage these errors using exception handling methods like try, catch, and finally. Proper error handling ensures smooth program execution even in unexpected scenarios, empowering you to effectively manage errors in your JavaScript projects.

Live masterclass