JavaScript Interview Question #144
How do you throw custom errors in JavaScript?
Generators, Browser Storage, Security & Advanced Runtime Concepts Senior Advanced
Quick Interview Answer
Use the throw statement to signal an exceptional condition. It is best practice to throw Error objects, or instances of custom Error subclasses, because they provide standard fields such as name, message, and stack information.
Detailed Explanation
Use the throw statement to signal an exceptional condition. It is best practice to throw Error objects, or instances of custom Error subclasses, because they provide standard fields such as name, message, and stack information.
Custom error classes are useful when callers need to distinguish domain-specific failures from general programming or infrastructure errors.
Code Example
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
function setAge(age) {
if (age < 0) {
throw new ValidationError(
"Age cannot be negative"
);
}
}