Throwing Custom Errors
While JavaScript provides several built-in error types (ReferenceError, TypeError, etc.), you will often encounter situations where you need to signal a problem that doesn't fit neatly into these categories, or you want to provide more specific information about what went wrong. This is where throwing custom errors comes in.
The throw statement allows you to create and throw your own error objects, which can then be caught by a try...catch block.
1. The throw Statement Revisited
The throw statement creates an exception (an error) that interrupts the normal flow of program execution. The execution immediately jumps to the nearest enclosing catch block.
Syntax: throw expression;
- The
expressioncan be any JavaScript value, but it is highly recommended to throw anErrorobject (or an instance of one of its subclasses). - Throwing primitive values (like strings or numbers) can make debugging harder because they lack important properties like
name,message, andstacktrace.
2. Throwing Built-in Error Objects
The most common way to throw a custom error is to create a new instance of the Error constructor or one of its built-in subclasses (TypeError, RangeError, etc.).
Syntax: throw new Error('Your custom message here');
When you create an Error object:
error.name: Defaults to"Error"(or the name of the specific subclass, e.g.,"TypeError").error.message: The string message you provide.error.stack: A string representing the call stack at the moment the error was thrown, invaluable for debugging.
3. Throwing Primitive Values (Avoid!)
While technically possible, throwing primitive values like strings, numbers, or booleans is generally considered a bad practice. They lack the useful name, message, and stack properties that Error objects provide, making debugging significantly harder.
4. Creating Custom Error Classes (Advanced)
For more complex applications, you might want to create your own custom error types by extending the built-in Error class. This allows you to:
- Create specific error names (e.g.,
NotFoundError,AuthenticationError). - Add custom properties to your error objects (e.g.,
statusCode,errorCode). - Use
instanceofto specifically check for your custom error types incatchblocks.
Syntax:
class CustomError extends Error {
constructor(message, customProperty) {
super(message); // Call the parent Error constructor
this.name = 'CustomError'; // Set a custom name
this.customProperty = customProperty; // Add custom data
}
}
Exercise: Throwing Custom Errors
Practice throwing and catching different types of errors, including a custom error class.

