Ask any question about JavaScript here... and get an instant response.
How can I create and throw a custom error in JavaScript within a try/catch block for better error handling?
Asked on Nov 26, 2025
Answer
To create and throw a custom error in JavaScript, you can define a new error class that extends the built-in Error class. This allows you to provide a custom message and additional properties if needed. Here's an example of how to do this within a try/catch block.
<!-- BEGIN COPY / PASTE -->
class CustomError extends Error {
constructor(message) {
super(message);
this.name = "CustomError";
}
}
try {
throw new CustomError("This is a custom error message");
} catch (error) {
console.error(`${error.name}: ${error.message}`);
}
<!-- END COPY / PASTE -->Additional Comment:
✅ Answered with JavaScript best practices.- The "CustomError" class extends the built-in "Error" class, allowing you to create errors with a custom name and message.
- In the "try" block, a new "CustomError" is thrown with a specific message.
- The "catch" block captures the error and logs its name and message to the console.
- This approach enhances error handling by allowing you to differentiate between different types of errors.
Recommended Links:
