JavaScript异常错误处理

来源:互联网 发布:网上做账软件 编辑:程序博客网 时间:2024/05/16 00:58

1.异常:

    当JavaScript引擎执行JavaScript代码时,发生了错误,导致程序停止运行

2.异常抛出:

    当异常产生,并且将这个异常生成一个错误信息

3.异常捕获:  

try{       发生异常的代码块     }catch(err){           错误信息处理}


<html><head><script>var txt="";function message(){   try{        addlert("welcome")        }    catch(err){         txt="本页有一个错误异常:"+err.message;         alert(txt);     }</script></head><body><input type="button" value="button" onclick="message()">      </body></html>


4.Throw语句通过throw语句创建一个自定义错误

function myFunction(){try  {  var x=document.getElementById("demo").value;  if(x=="")    throw "empty";  if(isNaN(x)) throw "not a number";  if(x>10)     throw "too high";  if(x<5)      throw "too low";  }catch(err)  {  var y=document.getElementById("mess");  y.innerHTML="Error: " + err + ".";  }}</script><h1>My First JavaScript</h1><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="mess"></p>



0 0
原创粉丝点击