Condividi tramite


Istruzione throw

Genera una condizione d'errore gestibile da un'istruzione try...catch...finally.

throw [exception]

Argomenti

  • eccezione
    Facoltativo. Qualsiasi espressione.

Note

L'istruzione throw può essere utilizzata senza argomenti, ma solo se è contenuta all'interno di un blocco catch. In tale situazione, l'istruzione throw genera di nuovo l'errore individuato dall'istruzione catch che la contiene. Quando viene specificato un argomento, l'istruzione throw genera il valore di exception.

Esempio

Nell'esempio seguente viene generato un errore che si basa su un valore passato, quindi viene illustrato il modo in cui tale errore viene gestito in una gerarchia di istruzioni try...catch...finally.

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.

Requisiti

Versione 5

Vedere anche

Riferimenti

Istruzione try...catch...finally

Oggetto Error