js异常处理

<script>
function myFunction()
{
try
{ 
var x=document.getElementById("demo").value;
if(x=="")    throw "值为空";
if(isNaN(x)) throw "不是数字";
if(x>10)     throw "太大";
if(x<5)      throw "太小";
}
catch(err)
{
var y=document.getElementById("mess");
y.innerHTML="错误:" + err + "。";
}
}
</script>
try {
    tryCode - 尝试执行代码块
}
catch(err) {
    catchCode - 捕获错误的代码块
} 
finally {
    finallyCode - 无论 try / catch 结果如何都会执行的代码块
}

实例:

 function catchErro() {
     try {
         if (arguments.length > 0) {
             arguments[0]();
         }

     } catch (err) {
         if (arguments.length > 1) {
             arguments[1](err);
         }

     } finally {
         if (arguments.length > 2) {
             arguments[2]();
         }

     }
 }
 catchErro(
     function () {
         log("函数执行try");
         throw "异常代码";
     },
     function (err) {
         log("函数捕获到异常" + err);
     },
     function () {
         log("函数执行finally");
     });


原文地址:https://www.cnblogs.com/embaobao/p/10720852.html