JavaScript throw statement
- Previous Page switch
- Next Page try...catch
- Go to the Previous Level JavaScript Statement Reference Manual
Definition and Usage
The throw statement throws (produces) errors.
When an error occurs, JavaScript usually stops and generates an error message.
Its technical term is: JavaScript will throw (throw) errors.
The throw statement allows you to create custom errors.
Its technical term is: throw an exception (exception).
Exceptions can be JavaScript strings, numbers, booleans, or objects:
throw "Too big"; // Throw text throw 500; // Throw a number
When used with try and catch, throw can control the program flow and generate custom error messages.
For more information on JavaScript errors, please refer to our JavaScript error tutorial.
Example
This example checks the input. If the value is incorrect, it throws an exception (err).
The catch statement catches the exception (err) and displays a custom error message:
<!DOCTYPE html> <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>
syntax
throw expression;
parameter value
parameter | description |
---|---|
expression | necessary. The exception to be thrown. It can be a string, number, boolean, or object. |
technical details
JavaScript version: | ECMAScript 3 |
---|
browser support
statement | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
throw | Support | Support | Support | Support | Support |
Related Pages
JavaScript Tutorial:JavaScript Errors
JavaScript Reference Manual:JavaScript try/catch/finally Statement
- Previous Page switch
- Next Page try...catch
- Go to the Previous Level JavaScript Statement Reference Manual