cover-img

Exception Handling in JavaScript

20 January, 2023

3

3

1

What is exception handling in JavaScript?

In JavaScript, an exception is a value that represents an error. It is the β€˜exception’ that happens when coding. Exceptions can be thrown (or re-thrown) within a try block and caught using a catch block.

Why do we need to handle exceptions?

Exception handling is useful for programmers because it allows them to handle errors in a structured way, which makes it easier to debug and maintain their code. It also provides a way to catch and handle errors before they cause the code to crash or have unexpected results. Exception handling is especially important in large applications, as it helps to ensure that the code is robust and can handle unexpected errors without crashing.

Example of How to Handle Exceptions

Here is an example of how to throw and catch an exception in JavaScript:

try {
// code that might throw an exception
throw new Error("Something went wrong");
} catch (error) {
// code to handle the exception
console.log(error.message);
}

The throw statement throws an exception. The exception can be a string, a number, a boolean, or an object. We throw a new Error object with a message in the example above.

The catch block catches the exception and provides an error object that you can use to learn more about the error that occurred. In the example above, we log the error message to the console.

It is also possible to use a finally block after the catch block. The finally block will always be executed, whether or not an exception was thrown or caught.

Here is an example with a finally block:

try {
// code that might throw an exception
throw new Error("Something went wrong");
} catch (error) {
// code to handle the exception
console.log(error.message);
} finally {
// code that is always executed, regardless of whether an exception was thrown or caught
console.log("Finally block executed");
}

It is also possible to nest try...catch blocks. In this case, the inner catch block will only handle exceptions thrown in the try block associated with. If an exception is thrown in an outer try block and is not caught, it will be passed to the next outer try...catch block, until it is caught or reaches the script's top level.

The Error Object

In JavaScript, the Error object is a base object for representing an error. It is a native object provided by JavaScript and not defined by the user.

The Error object has several properties, including:

  • name: a string that identifies the type of error
  • message: a string that describes the error
  • stack: a string that contains the stack trace of the error (available in modern browsers)

You can create an Error object using the new operator and the Error constructor function:

const error = new Error("Something went wrong");

You can also create a custom error object by defining a new object that has the Error object as its prototype:

function CustomError(message) {
this.name = "CustomError";
this.message = message;
}
CustomError.prototype = new Error();

const error = new CustomError("Something went wrong");

In addition to the Error object, there are several other built-in error objects in JavaScript, including:

  • EvalError: indicates an error in the eval() function
  • RangeError: indicates an error when a number is not within the expected range
  • ReferenceError: indicates an error when an invalid reference is used
  • SyntaxError: indicates an error in the syntax of a script
  • TypeError: indicates an error when a value is not of the expected type
  • URIError: indicates an error when a global URI handling function was used in an incorrect way

You can use these error objects in the same way as the Error object by using the new operator and the appropriate constructor function.

Re-throwing an Exception

In JavaScript, you can rethrow an error by simply throwing it again inside a catch block. This allows you to handle the error in one place but also pass it on to a higher level of the code for further handling.

Here is an example of how to rethrow an error in JavaScript:

try {
// code that might throw an error
throw new Error("Something went wrong");
} catch (error) {
// code to handle the error
console.log(error.message);
throw error; // rethrow the error
}

In the example above, we throw a new Error object with a message inside a try block. The catch block catches the error and logs the error message to the console. It then throws the error again, using the throw statement.

This allows the error to be caught by a higher-level catch block, or by the top-level code if there are no higher-level catch blocks.

It is also possible to modify the error before rethrowing it. For example, add additional information to the error message, or wrap the error in a new error object.

Here is an example of modifying the error before rethrowing it:

try {
// code that might throw an error
throw new Error("Something went wrong");
} catch (error) {
// code to handle the error
console.log(error.message);
const newError = new Error(`${error.message} (modified)`);
throw newError;
}

In the example above, we create a new Error object with a modified error message and then throw it again using the throw statement.

3

3

1

ShowwcaseHQ

San Francisco, CA, USA

Showwcase is where developers hang out and find new opportunities together as a community
Tapas Adhikary
Educator @tapaScript | Teaching JavaScript/React/FullStack | Writer | YouTuber | Founder reactplay.io

More Articles