Easy Tutorial
❮ Jsref Sethours Prop Document Doctype ❯

JavaScript throw Statement

JavaScript Statements Reference Manual

Example

This example checks the value of the input variable. If the value is incorrect, an exception (err) is thrown.

The exception (err) is caught by the catch statement and custom error messages are output:

<!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>

Definition and Usage

The throw statement throws an error.

When an error occurs, JavaScript stops execution and throws an error message.

The technical term for this situation is: JavaScript will throw an error.

The throw statement creates a custom error.

The technical term is: throw an exception.

The exception can be a JavaScript string, number, boolean, or object:

If used together with try and catch, you can control program flow and generate custom error messages.

For more JavaScript error information, please read our JavaScript Errors tutorial.


Browser Support

Statement Chrome Edge Firefox Safari Opera
throw Yes Yes Yes Yes Yes

Syntax

Parameter Values

Parameter Description
expression Required. The exception to be thrown. It can be a string, number, boolean, or object.

Technical Details

| JavaScript Version: | 1.4 | | --- | --- |


Related Pages

JavaScript Tutorial: JavaScript Errors

JavaScript Reference Manual: JavaScript try/catch/finally Statement


❮ Jsref Sethours Prop Document Doctype ❯