Loading lessons...
Throw and Custom Errors
Throw and Custom Errors
You can create your own errors with throw and catch them with try...catch.
The throw statement
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
}
Throw types
You can throw anything, but Error objects are best because they carry useful info:
throw new Error("message");
throw new TypeError("expected a number");
Handling a custom error
try {
divide(10, 0);
} catch (err) {
console.log(err.message); // "Cannot divide by zero"
}
Why use throw?
- Validate inputs before using them.
- Fail loudly and clearly instead of silently producing wrong results.
- Give useful messages to anyone using your function.
Validation example
function setAge(age) {
if (age < 0) {
throw new RangeError("Age cannot be negative");
}
return age;
}
TL;DR
- throw raises an error.
- new Error, TypeError, RangeError create typed errors.
- try...catch catches thrown errors.
- Use throw for input validation and clear failures.