From da78a9e329e272dedb2400b79a3bdeebff387d47 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:42:17 -0500 Subject: initial commit --- .../reference/statements/throw/index.html | 195 +++++++++++++++++++++ 1 file changed, 195 insertions(+) create mode 100644 files/it/web/javascript/reference/statements/throw/index.html (limited to 'files/it/web/javascript/reference/statements/throw') diff --git a/files/it/web/javascript/reference/statements/throw/index.html b/files/it/web/javascript/reference/statements/throw/index.html new file mode 100644 index 0000000000..1aecd9ca9a --- /dev/null +++ b/files/it/web/javascript/reference/statements/throw/index.html @@ -0,0 +1,195 @@ +--- +title: throw +slug: Web/JavaScript/Reference/Statements/throw +tags: + - JavaScript + - Statement +translation_of: Web/JavaScript/Reference/Statements/throw +--- +
{{jsSidebar("Statements")}}
+ +

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.

+ +
{{EmbedInteractiveExample("pages/js/statement-throw.html")}}
+ + + +

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

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{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')}} 
+ +

Compatibilità dei browser

+ + + +

{{Compat("javascript.statements.throw")}}

+ +

Vedi anche

+ + -- cgit v1.2.3-54-g00ecf