The throw
statement is valid in all contexts where statements can be used. Its execution generates an exception that penetrates through the call stack. For more information on error bubbling and handling, see Control flow and error handling.
The throw
keyword can be followed by any kind of expression, for example:
throw error;
throw new Error("Required");
In practice, the exception you throw should always be an Error
object or an instance of an Error
subclass, such as RangeError
. This is because code that catches the error may expect certain properties, such as message
, to be present on the caught value. For example, web APIs typically throw DOMException
instances, which inherit from Error.prototype
.