EXCEPCIONES EN JAVASCRIPT: CÓMO FUNCIONAN Y EJEMPLOS
Cuando se produce un error en javascript,se suele mostrar un error o se para la ejecución de la wbe pero con lasLa sintaxis es:
try {
//Se ejecuta el código y puede puede producir un error
}catch(error){
//Tartar el error
}
Ejemplo:
try {
funcion_inexistrente()
}catch(error){
if (error.description){
alert("Se ha producido el siguiente error: " + error.description)
}else{
alert("Se ha producido el siguiente error: " + error)
}
}
x = document.getElementById("idinputtext").value;
try {
if(x == ") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch (e) {
//tratamos la excepción
alert(e);
}