Expression throw en JavaScript
- Page précédente switch
- Page suivante try...catch
- Retour en haut de page Manuel de référence instructions JavaScript
Définition et utilisation
La directive throw lève (génère) des erreurs.
Lorsqu'une erreur se produit, JavaScript s'arrête généralement et génère un message d'erreur.
Son terme technique est : JavaScript lève (throw) des erreurs.
La directive throw permet de créer des erreurs personnalisées.
Its technical term is: throw an exception (exception).
Exceptions can be JavaScript strings, numbers, boolean values, or objects:
throw "Too big"; // Throw text throw 500; // Throw a number
When used with try and catch, throw can control the program flow and generate custom error messages.
For more information on JavaScript errors, please study our JavaScript error tutorial.
Example
This example checks the input. If the value is incorrect, it throws an exception (err).
The catch statement catches the exception (err) and displays a custom error message:
<!DOCTYPE html> <html> <body> <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() { var message, x; message = document.getElementById("message"); message.innerHTML = ""; 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> </body> </html>
syntax
throw expression;
parameter value
parameter | description |
---|---|
expression | necessary. The exception to be thrown. It can be a string, number, boolean value, or object. |
technical details
JavaScript version: | ECMAScript 3 |
---|
browser support
expression | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
throw | Support | Support | Support | Support | Support |
Pages associées
Tutoriel JavaScript :Erreurs JavaScript
Manuel de référence JavaScript :Instructions try/catch/finally JavaScript
- Page précédente switch
- Page suivante try...catch
- Retour en haut de page Manuel de référence instructions JavaScript