throw
L'istruzione throw
chiama un'eccezione definita dall'utente. L'esecuzione della funzione corrente si interrompe (ovvero i comandi successivi a throw
non verranno eseguiti), e il controllo verrà passato al primo blocco catch
nella pila delle chiamate. Se non è previsto nessun blocco catch
esiste nella funzione chiamante, il programma verrà terminato.
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
Il codice sorgente per questo esempio è disponibile su una repository di GitHub. Se ti piacerebbe contribuire al progetto interattivo d'esempio, clona https://github.com/mdn/interactive-examples e poi inviaci una pull request.
Sintassi
throw espressione;
espressione
- L'espressione da chiamare.
Descrizione
Usa l'istruzione throw
per chiamare un'eccezione. Quando chiami un'eccezione, l'espressione
specifica il valore dell'eccezione. Ognuna delle seguenti righe chiama un'eccezione.
throw 'Error2'; // genera un'eccezione con una stringa con valore Error2
throw 42; // genera un'eccezione con valore 42
throw true; // genera un'eccezione con valore true
Nota bene che l'istruzione throw
viene gestita dall'automatic semicolon insertion (ASI) e quindi non puoi andare a capo fra throw
e l'espressione.
Esempi
Chiama un oggetto
Puoi specificare un oggetto quando chiami un eccezione. In seguito puoi riportare le proprietà dell'oggetto nel blocco catch
. L'esempio seguente crea un oggetto di tipo UserException
e poi lo usa nell'istruzione throw
.
function UserException(message) {
this.message = message;
this.name = 'UserException';
}
function getMonthName(mo) {
mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec)
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
if (months[mo] !== undefined) {
return months[mo];
} else {
throw new UserException('InvalidMonthNo');
}
}
try {
// statements to try
var myMonth = 15; // 15 is out of bound to raise the exception
var monthName = getMonthName(myMonth);
} catch (e) {
monthName = 'unknown';
console.log(e.message, e.name); // pass exception object to err handler
}
Un altro esempio di chiamata ad un oggetto
L'esempio seguente testa una stringa in input per un codice postale di avviamento postale (CAP) americano. Se il CAP fornito è in un formato non valido, l'istruzione throw chiama un'eccezione creando un oggetto di tipo ZipCodeFormatException
.
/*
* Creates a ZipCode object.
*
* Accepted formats for a zip code are:
* 12345
* 12345-6789
* 123456789
* 12345 6789
*
* If the argument passed to the ZipCode constructor does not
* conform to one of these patterns, an exception is thrown.
*/
function ZipCode(zip) {
zip = new String(zip);
pattern = /[0-9]{5}([- ]?[0-9]{4})?/;
if (pattern.test(zip)) {
// zip code value will be the first match in the string
this.value = zip.match(pattern)[0];
this.valueOf = function() {
return this.value
};
this.toString = function() {
return String(this.value)
};
} else {
throw new ZipCodeFormatException(zip);
}
}
function ZipCodeFormatException(value) {
this.value = value;
this.message = 'does not conform to the expected format for a zip code';
this.toString = function() {
return this.value + this.message;
};
}
/*
* This could be in a script that validates address data
* for US addresses.
*/
const ZIPCODE_INVALID = -1;
const ZIPCODE_UNKNOWN_ERROR = -2;
function verifyZipCode(z) {
try {
z = new ZipCode(z);
} catch (e) {
if (e instanceof ZipCodeFormatException) {
return ZIPCODE_INVALID;
} else {
return ZIPCODE_UNKNOWN_ERROR;
}
}
return z;
}
a = verifyZipCode(95060); // returns 95060
b = verifyZipCode(9560); // returns -1
c = verifyZipCode('a'); // returns -1
d = verifyZipCode('95060'); // returns 95060
e = verifyZipCode('95060 1234'); // returns 95060 1234
Richiamare un'eccezione
Puoi usare throw
per richiamare un'eccezione dopo averla già gestita. L'esempio seguente gestisce un'eccezione con un valore numerico e la richiama se tale valore supera 50. Un'eccezione richiamata si propaga fino alla funzione che la racchiude oppure fino al livello più alto in modo che l'utente la veda.
try {
throw n; // throws an exception with a numeric value
} catch (e) {
if (e <= 50) {
// statements to handle exceptions 1-50
} else {
// cannot handle this exception, so rethrow
throw e;
}
}
Specifiche
Specification | Status | Comment |
---|---|---|
ECMAScript 3rd Edition (ECMA-262) | Standard | Definizione iniziale. Implementata in JavaScript 1.4 |
ECMAScript 5.1 (ECMA-262) The definition of 'throw statement' in that specification. |
Standard | |
ECMAScript 2015 (6th Edition, ECMA-262) The definition of 'throw statement' in that specification. |
Standard | |
ECMAScript (ECMA-262) The definition of 'throw statement' in that specification. |
Living Standard |
Compatibilità dei browser
BCD tables only load in the browser