Export (0) Print
Expand All

throw Statement (JavaScript)

Generates an error condition that can be handled by a try...catch...finally statement.

throw exception 

The required exception argument can be any expression.

The following example throws an error based on a passed-in value, and then illustrates how that error is handled in a hierarchy of try...catch statements:

function ThrowDemo(x) {
    try {
        try {
            // Throw an exception that depends on the argument.
            if (x == 0)
                throw new Error(200, "x equals zero");
            else
                throw new Error(201, "x does not equal zero");
        }
        catch (e) {
            // Handle the exception.
            switch (e.number) {
                case 200:
                    ShowLine(e.message + " - handled locally.");
                    break;
                default:
                    // Throw the exception to a higher level.
                    throw e;
            }
        }
    }
    catch (e) {
        // Handle the higher-level exception.
        ShowLine(e.message + " - handled higher up.");
    }
}

function ShowLine(s) {
    document.write(s);
    document.write("<br />");
}

ThrowDemo(0);
ThrowDemo(1);

// Output:
//  x equals zero - handled locally.
//  x does not equal zero - handled higher up.

Supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards. See Version Information.

Community Additions

Show:
© 2014 Microsoft