How does the throw
statement work?
The throw
statement in JavaScript is used to throw a user defined exception. An exception in programming, is when an unexpected event happens and disrupts the normal flow of the program.
As programmers it is important to handle these exceptions, so your programs don’t crash unexpectedly when errors occur. Here is the basic syntax for the throw
statement:
throw expression;
The expression
in this case would be the object or value that represents the exception you want to throw. Examples of this would be the built in exception classes like the Error
, TypeError
, or RangeError
class. Here is an example of using the throw
statement to throw a TypeError
:
function validateNumber(input) {
if (typeof input !== "number") {
throw new TypeError("Expected a number, but received " + typeof input);
}
return input * 2;
}
In this example, we are checking if the type of input
is not of type number
. If not, then we are throwing a TypeError
with a custom message. Otherwise, the function will return the result of multiplying the input
by 2
.
If you wanted to throw a more generic error message, then you can reference the Error
constructor like this:
function divide(numerator, denominator) {
if (denominator === 0) {
throw new Error("Cannot divide by zero");
}
return numerator / denominator;
}
Here is an example of a function that will check if the denominator is 0
. If that is the case, then it will throw a custom error message saying Cannot divide by zero
.
In the next lecture video, we will look at how to throw errors messages within the context of the try
/catch
block which is used to gracefully handle exceptions in JavaScript.