JavaScript Throw

Monday, April 16, 2012

The JavaScript throw statement allows you to create an exception. The throw statement is used in conjunction with the try and catch statements we learned about in the previous tutorial. The throw statement allows you to control the program flow. Here is an example of the throw syntax.

throw exception

The exception can be defined as an integer, string, Boolean, or an object. Here is an example of how to use the throw statement in conjuction with the try and catch JavaScript statements.

<script type="text/javascript">
    var x = prompt("Input a number between 10 and 20:", "");
        if (x < 10) {
            throw "errorLow";
        else if (x > 20) {
            throw "errorHigh";
        else {
            alert("Good job following directions!");
    catch (err) 
        if (err == "errorLow") {
            alert("Your number is less than 10.");
        if (err == "errorHigh") {
            alert("Your number is greater than 20.");

Did you find the page informational and useful? Share it using one of your favorite social sites.

Recommended Books & Training Resources

JavaScript and jQuery: The Missing Manual Professional JavaScript for Web Developers Murachs JavaScript and DOM Scripting