Javascript Throw Statement And Custom Errors Complete Guide

 Last Update:2025-06-22T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    6 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of JavaScript throw Statement and Custom Errors


Understanding the throw Statement in JavaScript

The throw statement in JavaScript is used to create and throw an error when a specified condition occurs. A common use case involves validating user input or function arguments and throwing an error if the input does not meet certain criteria. When a throw statement is encountered in a script, it stops the execution at that point, and then passes control to the nearest catch block within a try...catch structure. If no catch block is found, the error will cause the program to terminate and an error message will be displayed.

Syntax of the throw Statement

throw expression;
  • expression: The value to be thrown. This can be a primitive value like a number or string, but it is often an instance of an Error object (or one of its subclasses).

Throwing Exceptions Manually

To demonstrate the throw statement, consider the following example where we validate age input:

function checkAge(age) {
  if (age < 18) {
    throw new Error("Access denied - You must be at least 18 years old.");
  } else {
    console.log("Access granted - You are old enough!");
  }
}

try {
  checkAge(15);
} catch (error) {
  console.error(error.message);
}
// Output: Access denied - You must be at least 18 years old.

In this example:

  • We define a function checkAge which takes one parameter age.
  • Inside the function, if the age is less than 18, an error is thrown using the throw keyword.
  • The error message "Access denied - You must be at least 18 years old." is passed as a string to the Error constructor to create an Error object.
  • When the function is called with the value 15, the condition inside the if statement is true, so an Error is thrown.
  • The try block attempts to execute checkAge(15).
  • Since an error is thrown, the execution is immediately halted, and the control is transferred to the catch block.
  • In the catch block, we log the error message using console.error().

Error Objects in JavaScript

When you throw an error in JavaScript, you usually want to pass an error object rather than a plain string. Doing so provides additional information about the error, such as the name of the error and a stack trace.

Built-In Error Types

JavaScript has several built-in error types:

  • Error: The base class for all error types.
  • ReferenceError: An error that occurs when you refer to a variable or function that does not exist.
  • SyntaxError: An error that occurs when there is a mistake in your code's syntax.
  • TypeError: An error that occurs when you try to perform an operation on a type that is incorrect for that operation.
  • RangeError: An error that occurs when a numeric variable or parameter is outside its valid range.
  • UriError: Deprecated, was intended for invalid URI operations, now a generic TypeError.
  • AggregateError: Represents an error when multiple errors need to be wrapped in a single error.

These error objects can be instantiated using their respective constructors and can provide specific error information such as name, message, and stack.

Example with Built-In TypeError
function divide(a, b) {
  if (typeof a !== 'number' || typeof b !== 'number') {
    throw new TypeError('Both arguments must be numbers');
  }
  
  return a / b;
}

try {
  console.log(divide(10, '2'));
} catch (error) {
  console.error(error.name); // TypeError
  console.error(error.message); // Both arguments must be numbers
}

Creating Custom Error Types

Often, built-in error types are too broad or do not meet your specific needs. In these cases, you can create your own custom error types by extending the Error class. This allows you to add more context-specific information or override methods that might be useful.

Steps to Create Custom Error

  1. Create a Subclass of the Error Class: Use class and extends syntax.
  2. Modify the Constructor: Add fields or properties specific to your error.
  3. Override Methods (Optional): Customize behavior like logging additional information.

Here is a detailed example creating a custom ValidationError.

Creating a Custom ValidationError
class ValidationError extends Error {
  constructor(message, field) {
    super(message); // Call the parent class constructor with the parameters it needs
    this.name = 'ValidationError'; // Optionally set custom property
    this.field = field; // Optionally set custom property
  }
}

function createUser(user) {
  if (!user.name) {
    throw new ValidationError('Name is required', 'name');
  }

  if (user.age < 18) {
    throw new ValidationError('User must be at least 18 years old', 'age');
  }

  console.log('Creating user:', user);
}

const user = { name: '', age: 16 };

try {
  createUser(user);
} catch (error) {
  if (error instanceof ValidationError) {
    console.error(`Validation Error in Field: ${error.field}. Message: ${error.message}`);
  } else {
    console.error('An unexpected error occurred:', error.message);
  }
}

// Output: Validation Error in Field: name. Message: Name is required

In the above example:

  • We define a ValidationError subclass of the built-in Error class.
  • In the constructor, we call super(message) to initialize the base Error class with the given message but also add a custom field property to indicate which field caused the validation failure.
  • In the createUser function, we check if the user object has a valid name and age. If not, a ValidationError is thrown.
  • In the try block, we call createUser(user).
  • If a ValidationError is caught, we display both the field that caused the error and the error message.
  • For any other types of errors that might occur, we simply log the unexpected error message.

Important Information

  • Custom Error Benefits:

    • Better control over error handling.
    • More expressive error messages and easier debugging.
    • Allows categorization of errors within specific logic blocks.
  • Error Propagation:

    • If an error is thrown and not caught within the same block, it will propagate outwards to higher try...catch blocks.
    • If it reaches the top level without being caught, the program will crash and log the error message to the console.
  • Good Practices:

    • Use descriptive error messages.
    • Throw errors in response to actual problems and expected cases.
    • Always ensure your catch blocks handle errors gracefully.
    • Log errors effectively with necessary context for debugging purposes.
  • Error Properties:

    • name: The name of the error (usually a string).
    • message: The error message, providing more detail about what went wrong.
    • stack: A stack trace, showing where the error originated in the code.

With these principles and examples in mind, you can effectively manage and throw exceptions in JavaScript, making your applications more robust and easier to debug.


Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement JavaScript throw Statement and Custom Errors

Introduction to throw Statement

In JavaScript, the throw statement lets you create a custom error. When JavaScript encounters a throw statement, it stops and generates an error which must be handled, typically with a try...catch block.

Basic Example of throw

Let's start with a simple throw statement. We'll throw an error if a variable x is less than 5.

try {
    let x = 3;
    
    if(x < 5) {
        throw "Value is too low";
    }
    console.log(x);
} catch(err) {
    console.error(err);  // Output: Value is too low
}

Explanation:

  1. try block: Code that might cause an error is placed inside a try block.
  2. if condition: Checks if x is less than 5.
  3. throw statement: If the condition is true, a string message "Value is too low" is thrown as an error.
  4. catch block: The error thrown in the try block is caught here, and console.error is used to log the error message.

Example: Throwing a Number

In addition to strings, you can throw other types of data including numbers, boolean values, or even objects.

try {
    let age = 17;
    
    if(age < 18) {
        throw 18;
    }
    console.log("You can vote!");
} catch(err) {
    console.error(`You must be ${err} years old to vote.`);
    // Output: You must be 18 years old to vote.
}

Explanation:

  1. try block: We check if age is less than 18.
  2. throw statement: If the condition is true, the number 18 is thrown.
  3. catch block: The error (which is 18 in this case) is caught, and a message is displayed using template literals.

Custom Error Objects

For more structured error handling, you can throw and catch custom error objects.

Creating a Custom Error Constructor

Top 10 Interview Questions & Answers on JavaScript throw Statement and Custom Errors

Top 10 Questions and Answers: JavaScript throw Statement and Custom Errors

1. What is the throw statement in JavaScript?

Example:

function checkNumber(num) {
    if (num < 5) {
        throw new Error("Number is too low");
    }
    return num;
}

try {
    checkNumber(3);
} catch (error) {
    console.error(error.message);  // Output: Number is too low
}

2. Can I throw a custom error in JavaScript? If yes, how do I create one?

Yes, you can create and throw custom errors in JavaScript by extending the Error object. Custom errors allow you to add more specific information about the nature of the error and make it easier to debug and handle.

Example:

class CustomError extends Error {
    constructor(message, statusCode) {
        super(message);
        this.statusCode = statusCode;
    }
}

throw new CustomError("A custom error occurred", 500);

3. Can I throw a string instead of an Error object in JavaScript?

While you can throw a string or any other data type in JavaScript, it's generally recommended to throw an instance of the Error object or an object derived from Error. Throwing an Error object helps in maintaining consistency in error handling and provides useful properties like stack and message.

Example:

try {
    throw new Error("This is an error message");
} catch (error) {
    console.error(error.message); // Output: This is an error message
    console.error(error.stack);   // Output: The stack trace
}

4. Why should I use custom errors in JavaScript?

Using custom errors in JavaScript enhances the clarity and reliability of your error handling mechanism. Custom errors provide better context about what went wrong, which simplifies debugging. They allow you to define specific error types that can be caught and handled separately, making your code more robust and maintainable.

5. Can I add additional properties to a custom error in JavaScript?

Yes, you can add additional properties to a custom error in JavaScript by extending the Error object or creating a class that inherits from Error. This lets you provide more context about the error, such as status codes, user IDs, or error codes.

Example:

class CustomError extends Error {
    constructor(message, statusCode, errorCode) {
        super(message);
        this.statusCode = statusCode;
        this.errorCode = errorCode;
    }
}

try {
    throw new CustomError("Database error", 503, "DB_TIMEOUT");
} catch (error) {
    console.error(error.message);     // Output: Database error
    console.error(error.statusCode);  // Output: 503
    console.error(error.errorCode);   // Output: DB_TIMEOUT
}

6. How do I use throw to validate input in functions?

You can use the throw statement to perform input validation in functions by checking the parameters passed to the function. If the parameters do not meet the expected criteria, you can throw an error to indicate the issue.

Example:

function divideNumbers(a, b) {
    if (typeof a !== 'number' || typeof b !== 'number') {
        throw new TypeError('Both arguments must be numbers');
    }
    if (b === 0) {
        throw new RangeError('The denominator must not be zero');
    }
    return a / b;
}

try {
    console.log(divideNumbers(10, 0));
} catch (error) {
    console.error(error.message); // Output: The denominator must not be zero
}

7. What is the difference between throw and return in JavaScript?

  • return: The return statement is used to return a value from a function and terminate its execution.

  • throw: The throw statement is used to throw an error and terminate the execution of a function, usually to be caught and handled by a try...catch block.

Example:

function calculateArea(radius) {
    if (radius < 0) {
        throw new RangeError("Radius cannot be negative");
    }
    return Math.PI * radius * radius;
}

try {
    const area = calculateArea(-5);
} catch (error) {
    console.error(error.message); // Output: Radius cannot be negative
}

8. How can I create a detailed custom error with multiple pieces of information?

You can create detailed custom errors by adding multiple properties to the custom error class. Using a custom error class allows you to add as many properties as needed to provide comprehensive information about the error.

Example:

class DetailedError extends Error {
    constructor(message, statusCode, errorCode, subsystem, timestamp) {
        super(message);
        this.statusCode = statusCode;
        this.errorCode = errorCode;
        this.subsystem = subsystem;
        this.timestamp = timestamp;
    }
}

const error = new DetailedError(
    "Failed to connect to database",
    500,
    "DB_CONNECTION_ERROR",
    "DatabaseService",
    new Date().toISOString()
);

console.error(error.message);     // Output: Failed to connect to database
console.error(error.statusCode);  // Output: 500
console.error(error.errorCode);   // Output: DB_CONNECTION_ERROR
console.error(error.subsystem);   // Output: DatabaseService
console.error(error.timestamp);   // Output: (current timestamp)

9. How can I interact with the Error object using throw?

When you throw an Error object, you can access its properties such as message, name, and stack within the catch block. This information can be used for debugging and logging.

Example:

try {
    throw new Error("An unexpected error occurred");
} catch (error) {
    console.error(error.name);      // Output: Error
    console.error(error.message);   // Output: An unexpected error occurred
    console.error(error.stack);     // Output: The stack trace where the error occurred
}

10. How can I differentiate between different types of errors in JavaScript?

You can differentiate between different types of errors in JavaScript by using several techniques. One common approach is to throw different classes of custom error objects, each representing a specific type of error. In your catch block, you can then use instanceof to determine the type of error.

Example:

You May Like This Related .NET Topic

Login to post a comment.