Throwing errors with throw
Learn to throw your own errors and when to use it.
Throwing errors with throw
In JavaScript the throw keyword lets you throw your own error. When an error is thrown, execution stops and jumps to the nearest catch block. You can pass an Error object or a string to throw; an Error object is more informative because it carries a stack trace.
Example: throw new Error("Invalid value"). This call immediately creates an error and if catch does not handle it the application crashes. throw is especially useful to signal business logic errors: for example when a negative age arrives you throw and stop the operation.
When to use throw?
You use throw for business logic errors. For example if a function receives a negative age that is not sensible; in this case you throw and let the caller handle it with catch.
Example: function setAge(age) { if (age < 0) throw new Error("Negative age"); }. Here when throw runs the function exits and the error is propagated to the caller. This is safer than silently continuing with bad data, because the problem is noticed earlier.
Exercise Negative age check with throw
Define a function called setAge. It should take an age parameter. In the body check with if (age < 0); when the condition holds call throw new Error("Negative age"). Then call this function inside a try block as setAge(-5); in a catch (e) block call console.error(e.message).
Show example solution
function setAge(age) {
if (age < 0) {
throw new Error("Negative age");
}
}
try {
setAge(-5);
} catch (e) {
console.error(e.message);
}
Test yourself
-
What is the effect of throw new Error("Negative age")?
throw new Error("Negative age");- Only writes a warning to the console, code continues
- Makes the variable undefined
- Ignores the throw line and continues
- Stops the code; without catch the app crashes
Show answer
Stops the code; without catch the app crashes — Correct. throw stops the code and without catch the app crashes.
-
Complete the throw statement
function checkAge(age) { if (age === null) { ____ new Error("Age required"); } }Show answer
function checkAge(age) { if (age === null) { throw new Error("Age required"); } } -
Match throw expressions to their meaning
- throw new Error("X")
- throws an Error object
- throw "X"
- throws a string
- throw 42
- throws a number
- throw; (only throw)
- gives a SyntaxError