Skip to content

Exception Handling in JavaScript

  • by

Exception handling is an essential feature of JavaScript that involves identifying and addressing errors or unusual conditions that arise while running a program. JavaScript programs can encounter exceptions due to a range of factors, including incorrect input, network glitches, or coding mistakes.

There are multiple approaches available in JavaScript to manage and control exceptions:

1. Try-Catch statement: To manage exceptions in JavaScript, the try-catch statement is used. The try block includes the code that may result in an exception, and any exceptions thrown are caught and dealt with in the catch block.

try {
  // code that may throw an exception
} catch (error) {
  // handle the exception
}

2. Throw statement:

The throw statement is utilized to manually initiate an exception in JavaScript. It is beneficial when you need to establish a personalized exception to manage a particular error situation.

throw new Error('Invalid input');

3. Finally block:

The finally block in JavaScript specifies code that must execute irrespective of whether an exception occurs or not. This block is not compulsory and is usually employed for completing operations or releasing resources.

try {
  // code that may throw an exception
} catch (error) {
  // handle the exception
} finally {
  // code that should be executed regardless of whether an exception is thrown or not
}

4. Error object:

JavaScript uses an error object to represent an exception that has been encountered. This error object comprises various properties, including name, message, and stack, which can be utilized to obtain more information about the exception.

try {
  // code that may throw an exception
} catch (error) {
  console.log(error.name);      // prints the name of the error
  console.log(error.message);   // prints the error message
  console.log(error.stack);     // prints the stack trace of the error
}

Exception Handling in JavaScript example

Simple example code.

<!DOCTYPE html>
<html>
<body>
    <script>
       function divide(x, y) {
        try {
            if (y === 0) {
            throw new Error("Cannot divide by zero.");
            } else {
                return x / y;
            }
        } catch (error) {
            console.log(error.message);
        } finally {
            console.log("Division operation complete.");
        }
        }

        console.log(divide(6, 2)); // Output: 3
        console.log(divide(6, 0)); 

    </script>
</body>
</html>

Output:

Exception Handling in JavaScript

Types of Errors

In JavaScript, errors can be classified into several types based on their nature and occurrence. Here are some of the common types of errors in JavaScript:

  1. Syntax errors: These occur when there are errors in the syntax of the code, such as missing or incorrect brackets, semicolons, or parentheses.
  2. Runtime errors: These occur when the code is syntactically correct but encounters issues during runtime, such as undefined variables or functions, or division by zero.
  3. Logic errors: These occur when the code runs without any errors or exceptions, but the output is not as expected due to issues in the program’s logic or algorithms.

Comment if you have any doubts or suggestions on this Js Exception Handling topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading