JavaScript lancia
Esempio
Questo esempio esamina l'input.
Se il valore è errato, viene generata un'eccezione (err):
<p>Please input a number between
5 and 10:</p>
<input id="demo" type="text">
<button type="button"
onclick="myFunction()">Test Input</button>
<p id="message"></p>
<script>
function myFunction() {
const message = document.getElementById("message");
message.innerHTML = "";
let x =
document.getElementById("demo").value;
try {
if(x == "") throw "is Empty";
if(isNaN(x)) throw "not a number";
if(x > 10) throw "too high";
if(x < 5) throw "too low";
}
catch(err) {
message.innerHTML =
"Input " + err;
}
}
</script>
Definizione e utilizzo
L' throw
istruzione consente di creare un errore personalizzato.
L' throw
istruzione genera (genera) un errore.
Il termine tecnico per questo è:
L' throw
istruzione genera un'eccezione .
L'eccezione può essere una stringa JavaScript, un numero, un booleano o un oggetto:
throw "Too big"; // throw a text
throw 500; // throw a number
throw false; // throw a boolean
throw person; // throw an object
Nota
L'uso di throw con try and catch , consente di controllare il flusso del programma e generare messaggi di errore personalizzati.
Guarda anche:
Sintassi
throw expression;
Parametri
Parameter | Description |
expression | Required. The exception to throw. Can be a string, number, boolean, or an object |
Supporto browser
break
è una funzione ECMAScript3 (ES3).
ES3 (JavaScript 1999) è completamente supportato in tutti i browser:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |