JavaScript throwStatement
JavaScript Statement Reference
Example
This example checks the value of an input variable. If the value is wrong, an exception (err) is thrown.
The exception (err) is caught by the catch statement and a custom error message is output:
<html>
<body>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="message"></p>
<script>
function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "is Empty";
if(isNaN(x)) throw "not a number";
if(x > 10) throw "too high";
if(x < 5) throw "too low";
}
catch(err) {
message.innerHTML = "Input " + err;
}
}
</script>
</body>
</html>
Try it Yourself »
Definition and Usage
The throw statement throws an error.
When an error occurs, JavaScript stops executing and throws an error message.
The technical term for this situation is: JavaScript will throw an error.
throwThe statement creates custom errors.
The technical term is:throw an exception。
The exception can be a JavaScript string, number, boolean, or object:
throw 500; // throw number
If you use throw withtry and catchtogether, you can control the program flow and generate custom error messages.
For more on JavaScript errors, read ourJavaScript ErrorsTutorial.
Browser Support
| Statement | |||||
|---|---|---|---|---|---|
| throw | Yes | Yes | Yes | Yes | Yes |
Syntax
Parameter Values
| Parameter | Description |
|---|---|
| expression | Required. The exception to throw. Can be a string, number, boolean, or object. |
Technical Details
| JavaScript Version: | 1.4 |
|---|
Related Pages
JavaScript Tutorial:JavaScript Errors
JavaScript Reference:JavaScript try/catch/finally Statement
JavaScript Statement Reference Other Extensions