JavaScript Fundamentals · Error Handling · Lesson 31 of 48
Throwing Your Own Errors
Concept
Throwing Your Own Errors
The throw keyword lets your own functions signal that something went wrong, using the built-in Error object or a custom message.
Throwing immediately stops the current function, unwinding up the call stack until a matching catch block handles it — or, if none exists, crashing the program.
By the end of this lesson
- Explain the core idea behind Throwing Your Own Errors.
- Predict output before running a change.
- Test one realistic and one unusual input.
- Use the result to make the next decision.
How to study this page
- 1. Read one concept.
- 2. Change the example.
- 3. Run, compare, and explain.
- 4. Complete the challenge below.
Syntax
throw new Error("message");ExampleRunnable
function withdraw(balance, amount) {
if (amount > balance) {
throw new Error("Insufficient funds");
}
return balance - amount;
}
try {
withdraw(50, 100);
} catch (error) {
console.log(error.message);
}Try it Yourself »Custom error types
class ValidationError extends Error {}
try {
throw new ValidationError("Invalid input");
} catch (error) {
console.log(error instanceof ValidationError);
}Note: Extending Error lets you create custom error types that can be identified with instanceof, useful when different errors need different handling.
Self-check before continuing
Without looking at the example, describe what changes when you modify one input in Throwing Your Own Errors. Then reopen the editor and prove your explanation with a small test.
You are ready to continue when you can predict, test, and explain the result.
Your turn
Write a function divide(a, b) that throws an Error when b is 0, then call it inside a try/catch.
Loading editor…
Console