Throw in JavaScript

Exception handling in JavaScript involves managing errors or unexpected situations that occur while a program is running. It enables developers to address failures effectively and prevent the program from terminating abruptly by utilizing the error-handling mechanisms provided by JavaScript.

The primary mechanism for exception handling in JavaScript is the try...catch statement. Here's how it works:

  • Try block: A try block contains the code that you wish to keep an eye out for exceptions.
  • Catch block: You may add a catch block that tells you what to do if an exception arises inside the try block right after the try block. You may specify how to handle the problem, such as recording it or giving the user an error message inside the catch block.
  • Finally, block (optional): Following the catch block, you may want to add a finally block. Whether or not there was an exception in the try block, the code inside the finally block will always run. This is helpful for clearing out things like resources.

Example:

Example

try {
    // Code that may throw an exception
    let result = someFunction();
    console.log(result);
} catch (error) {
    // Handle the error
    console.error('An error occurred:', error.message);
} finally {
    // Cleanup code (optional)
    console.log('Cleanup tasks here');
}

In JavaScript exception handling, the throw statement is employed to deliberately generate and "throw" an exception. This allows developers to distinctly indicate the occurrence of a bug or any unexpected scenario in their code. When a throw statement is executed, the program stops running and shifts control to the catch clause within the nearest enclosing try block. If there is no such block, the control is passed to the global error handler.

Syntax:

Example

throw expression;

In this scenario, the term "expression" refers to the value intended to be thrown, typically an error object. While any data type can serve as this expression, it is commonly employed to throw instances of the Error object that is built-in, or any of its derived classes, to provide more detailed error descriptions.

Demonstration of Throw in JavaScript

Below are some instances showcasing how the throw statement is utilized in managing exceptions in JavaScript:

  • Creating a custom error message by throwing an error:

Code:

Example

function validateAge(age) {
    if (age < 0) {
        throw new Error('Age cannot be negative');
    }
    return 'Age is valid';
}

try {
    console.log(validateAge(-5));
} catch (error) {
    console.error('An error occurred:', error.message);
}

The function validateAge verifies whether the age parameter is negative, triggering an error message if so. To handle any exceptions that may arise, a try...catch block is implemented.

1. Throwing a specific error type:

Code:

Example

function fetchUser(id) {
    if (!id) {
        throw new TypeError('ID cannot be empty');
    }
    // Simulate fetching user data
    return { id: id, name: 'John Doe' };
}

try {
    console.log(fetchUser());
} catch (error) {
    console.error('An error occurred:', error.message);
}

In situations where y does not equal zero, an error object will be thrown by the division method. To handle this, any exceptions are captured and then recorded in the console through a try...catch block.

2. Throwing an error with additional information:

Code:

Example

function divide(a, b) {
    if (b === 0) {
        throw new Error(`Division by zero: ${a} / ${b}`);
    }
    return a / b;
}

try {
    console.log(divide(10, 0));
} catch (error) {
    console.error('An error occurred:', error.message);
}

In the case where an input is determined to be false, the validateInput function generates a ValidationError containing details about the invalid input and a customizable error message. This function takes both a message and an input as parameters, inherits from the Error class, and records an exception if the type of error is a ValidationError.

3. Throwing a custom error object:

Code:

Example

class CustomError extends Error {
    constructor(message) {
        super(message);
        this.name = 'CustomError';
    }
}

function processInput(input) {
    if (!input) {
        throw new CustomError('Input cannot be empty');
    }
    // Process the input
    return `Processed input: ${input}`;
}

try {
    console.log(processInput(''));
} catch (error) {
    console.error('An error occurred:', error.message);
}
  • The built-in Error class is extended with the definition of the ValidationError class.
  • Its constructor uses super to set the values after receiving an input and a message.
  • When an input is found to be false, the validateInput method throws a ValidationError.
  • ValidateInput(null) is invoked inside the try...catch block, which raises an exception.
  • The ValidationError is caught by the catch block, which also records the error message and incorrect input to help identify it apart from other problems.

This article provides a comprehensive explanation of how exception handling works in JavaScript, focusing specifically on the try...catch and throw statements. It illustrates the effective use of these mechanisms to gracefully manage errors, ensuring that applications can respond to issues without abrupt termination.

The throw keyword facilitates the creation and throwing of custom error objects, whereas the try...catch keyword acts as the primary mechanism for handling exceptions. By following the guidance provided in this article, developers can enhance the robustness and reliability of their code.

Input Required

This code uses input(). Please provide values below: