throw Statement

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

throw [exception]

Arguments

  • exception
    Optional. Any expression.

Remarks

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.

Example

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.

Requirements

Version 5

See Also

Reference

try...catch...finally Statement

Error Object