Exception Handling In JavaScript – Doing It The Right Way

What is Exception Handling?

The process of transforming a coding error message into a user-friendly error message is known as exception handling. It is a crucial stage in the development process. You can appropriately manage some of the challenges we experience as developers by using exceptions.

We will look at exception handling with JavaScript in this tutorial. Please also read our article on JavaScript Events.

To create an exception in JavaScript, we use the throw statement. The throw statement throws an exception whenever an abnormal condition arises. The thrown exception is handled by wrapping the code into the try/catch block. 

If an error should occur, the catch block is run; otherwise, just the try block instructions are executed. If this is unclear, don't worry; we will discuss the above in greater depth later in this article.

Types of JavaScript Errors

  1. Syntax Errors: These errors are ones that the computer cannot comprehend. These errors prevent the software from running.

Here are instances that you can refer to as syntax errors:

  • Spelling errors (i.e., Spelling parameter as parametre)
  • Omission of key characters, such as failing to use a semicolon to complete a statement.
  • Use of incorrect indentation

2. Runtime errors: These occur during the execution process. When your software runs, the problems are discovered. It either crashes or throws an exception. As a result, exception handlers deal with exception errors.

These mistakes are frequently caused by the following:

  • The program is unable to locate data because it doesn't exist.
  • The data is of an invalid kind.

3. Logical Errors: These errors do not generate an error or even an exception. This occurs because they are the result of the code failing to achieve what the developer intended. It takes time to uncover logical errors. They can only be discovered by extensive testing.

Error Objects in JavaScript

When an error occurs during program execution, i.e., during runtime, the throw statement throws such an error by producing an Error object.

When an exception occurs, the throw statement immediately creates and throws an Error object. You may utilize the Error object as a starting point for constructing custom exceptions, often known as user-defined exceptions. The Error object has the two characteristics shown below:

  • Name: This is used to return or set the name of an error.
  • Message: The "message" property returns an error message as a string.

Although Error is a generic constructor, these are the error constructors beside it:

  • InternalError: Whenever the JavaScript engine throws internal errors, it produces an instance.
  • EvalError: This function creates an instance of an error in the eval() function - a global function used to evaluate the javascript string code.
  • TypeError: It produces an error instance. Whenever a variable is of a different type.
  • SyntaxError: It creates a syntax error object that may arise during parsing the eval().
  • RangeError: These errors occur when a numeric value falls outside the set range.
  • URIError: The decodeURI() and encodeURI() functions throw a URIError exception.

Handling JavaScript Exceptions

You've now completed half of this topic, and by now, we hope you understand what exceptions in JavaScript are.

It's time to understand how to deal with them, so our code stays stable. Exceptions are handled in JavaScript using throw and try-catch-finally statements.

Important Terms

  • A try-catch-finally statement is a piece of code or a program that deals with exceptions.
  • The try clause executes the exception-generating code.
  • The catch clause catches exceptions that are thrown.
  • "Finally" clauses are always executed.
  • Exceptions are generated via the throw statement.

The Try-catch Technique For Exception Handling in JavaScript

The try-catch technique is the primary method of dealing with JavaScript exceptions, as it is in many other programming languages. In a word, a try-catch block is a code block that may be used to handle errors without disrupting the execution of your program. To put it another way, you can "attempt" to execute a piece of code and "catch" exceptions thrown.

Catching all Exceptions

Catching JavaScript exceptions is as simple as wrapping an expression in a try-catch statement. This method would catch all and any exceptions thrown without any further configuration.

try {
  // ...
} catch (e) {
  // ...
}

While this is a relatively simple error-handling method, it is crucial to remember that the exception caught always represents an implementation of the Js Error object, which has some helpful attributes such as a human-readable error description. This enables you to log these errors for debugging purposes.

try {
  // ...
} catch (e) {
  console.log(e);
}

Catching Specific Exceptions

Generally, capturing every exception thrown is not good practice. Instead of implementing a catchall, it is significantly more feasible to precisely catch and react to exceptions you anticipate. Verify the exception instance type before responding to them.

try {
  // ...
} catch (e) {
   if ( e instanceof CustomExceptionError ) {
    // ...
  }
}

While JavaScript allows you to include conditionals within the catch definition, this is deemed non-standard behavior. Thus the most reliable approach to creating conditional catch clauses is to utilize a conditional block in the catch to check for and react to error instances.
Keeping this in mind, it is easy to see how a simple try-catch may be stretched into a much more sophisticated process, allowing you to handle mistakes (errors) in various ways.

try {
  // ...
} catch (e) {
 if ( e instanceof CustomExceptionError ) {
    // ...
  } else if ( e instanceof OtherExceptionError ) {
    // ...
  } else {
    // ...
  }
}

Throw Statement

function myFunction() {
    const a = 40;
    const b = 0;
    try {
        if (y === 0) {
            throw ("This error is a division by the number zero");
        } else {
            const z = a / b;
        }
    } catch (error) {
        alert("Error: " + error);
    }
}

Try-Catch-Finally Statements

function myFunction() {
    const x = 60;
    try {
        alert("The value of x is : " + x);
    } catch (error) {
        alert("Error: " + error.message);
    } finally {
        alert("Finally: Finally will be executed")
    }
}