Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Export (0) Print
Expand All
Important This document may not represent best practices for current development, links to downloads and other resources may no longer be valid. Current recommended version can be found here.

throw Statement

Updated: August 2009

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

throw [exception]

exception

Optional. Any expression.

The throw statement can be used without an argument, but only if the throw statement is contained within a catch block. In that situation, the throw statement re-throws the error caught by the enclosing catch statement. When an argument is provided, the throw statement throws the value of exception.

The following example throws an error based on a passed-in value, then illustrates how that error is handled in a hierarchy of try...catch...finally 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:
                    print (e.message + " - handled locally.");
                    break;
                default:
                    // Throw the exception to a higher level.
                    throw e;
                }
        }
    }
    catch(e)
    {
        // Handle the higher-level exception.
        print (e.message + " - handled higher up.");
    }
}

ThrowDemo (0);
ThrowDemo (1);

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

Date

History

Reason

August 2009

Modified example.

Information enhancement.

Community Additions

ADD
Show:
© 2015 Microsoft