Instrucción throw de JavaScript
- Página anterior switch
- Página siguiente try...catch
- Volver a la capa superior Manual de referencia de instrucciones de JavaScript
Definición y uso
La instrucción throw lanza (produce) errores.
Cuando ocurre un error, JavaScript generalmente se detendrá y generará un mensaje de error.
Su terminología técnica es: JavaScript lanzará (throw) errores.
La instrucción throw permite crear errores personalizados.
Its technical term is: throw an exception (exception).
Exceptions can be JavaScript strings, numbers, booleans, 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, or object. |
technical details
JavaScript version: | ECMAScript 3 |
---|
browser support
statement | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
throw | Soporte | Soporte | Soporte | Soporte | Soporte |
Páginas relacionadas
Tutoriales de JavaScript:Errores de JavaScript
Manual de referencia de JavaScript:Sentencia try/catch/finally de JavaScript
- Página anterior switch
- Página siguiente try...catch
- Volver a la capa superior Manual de referencia de instrucciones de JavaScript