Path: blob/main/files/en-us/web/javascript/reference/statements/throw/index.md
6520 views
------{{jsSidebar("Statements")}}
The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.
{{EmbedInteractiveExample("pages/js/statement-throw.html")}}
Syntax
expression: The expression to throw.
Description
Use the throw statement to throw an exception. When you throw an exception, expression specifies the value of the exception. Each of the following throws an exception:
Also note that the throw statement is affected by automatic semicolon insertion (ASI) as no line terminator between the throw keyword and the expression is allowed.
Examples
Throw an object
You can specify an object when you throw an exception. You can then reference the object's properties in the catch block. The following example creates an object of type UserException and uses it in a throw statement.
Another example of throwing an object
The following example tests an input string for a U.S. zip code. If the zip code uses an invalid format, the throw statement throws an exception by creating an object of type ZipCodeFormatException.
Rethrow an exception
You can use throw to rethrow an exception after you catch it. The following example catches an exception with a numeric value and rethrows it if the value is over 50. The rethrown exception propagates up to the enclosing function or to the top level so that the user sees it.
Specifications
{{Specifications}}
Browser compatibility
{{Compat}}
See also
{{jsxref("Statements/try...catch", "try...catch")}}
{{jsxref("Global_Objects/Error", "Error")}}