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.


<html>
<body>
<script type="text/javascript">
    var x = prompt("Input a number between 10 and 20:", "");
    try 
    {
        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.");
        }
    }
</script>
</body>
</html>

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

Recommended Books & Training Resources

Professional JavaScript for Web Developers HTML CSS and JavaScript Editor JavaScript and jQuery: The Missing Manual