THE WORLD'S LARGEST WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

JavaScript throw Statement

JavaScript Statements Reference JavaScript Statements Reference

Example

This example examines input. 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 displayed:

<!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>
Try it yourself »

Definition and Usage

The throw statement throws (generates) an error.

When an error occurs, JavaScript will normally stop, and generate an error message.

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

The throw statement allows you to create a custom error.

The technical term for this is: throw an exception.

The exception can be a JavaScript String, a Number, a Boolean or an Object:

throw "Too big";    // throw a text
throw 500;          // throw a number

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

For more information about JavaScript errors, read our JavaScript Errors Tutorial.


Browser Support

Statement
throw Yes Yes Yes Yes Yes

Syntax

throw expression;

Parameter Values

Parameter Description
expression Required. The exception to throw. Can be a string, number, boolean or an object

Technical Details

JavaScript Version: 1.4

Related Pages

JavaScript Tutorial: JavaScript Errors

JavaScript Reference: JavaScript try/catch/finally Statement


JavaScript Statements Reference JavaScript Statements Reference