--- title: throw slug: Web/JavaScript/Reference/Statements/throw tags: - JavaScript - Statement translation_of: Web/JavaScript/Reference/Statements/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.
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.
throw espressione;
espressioneUsa 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.
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
}
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
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;
}
}
| Specification | Status | Comment |
|---|---|---|
| {{SpecName('ES3')}} | {{Spec2('ES3')}} | Definizione iniziale. Implementata in JavaScript 1.4 |
| {{SpecName('ES5.1', '#sec-12.13', 'throw statement')}} | {{Spec2('ES5.1')}} | |
| {{SpecName('ES6', '#sec-throw-statement', 'throw statement')}} | {{Spec2('ES6')}} | |
| {{SpecName('ESDraft', '#sec-throw-statement', 'throw statement')}} | {{Spec2('ESDraft')}} |
{{Compat("javascript.statements.throw")}}