try抛出异常,catch捕获异常
格式:
try{
}catch(error){
}
执行:首先去运行try中的代码如果正常则不运行catch,如果try中代码碰到异常,就跳过try异常后面的代码,直接去执行catch中的代码进行补救。其中catch中参数error错误对象,可以输出错误信息
【注】经常用于测试代码。
try{
alert("我是测试代码1"); //正常执行
alert(a); //报错直接跳到catch
alert("我是测试代码2");
}catch(error){
alert("我是补救代码 :" + error);
//我是补救代码 :ReferenceError: a is not defined
}
try throw catch
语法格式:
try{
尝试执行的代码;
throw new Error(参数);
}catch(error){
补救的代码;
}
执行过程:
1、我们先去执行try中的代码
2、执行的过程中,如果try中的代码执行异常,或者遇到throw,throw手动抛出的异常,我们就直接去执行catch中的代码。
3、catch中,我们可以通过error,获取错误信息,throw可以跟一个错误对象(错误解释)。
try{
alert("执行代码1");
alert("执行代码2");
throw new Error("这是演习,演习!");
}catch(error){
alert("补救代码 :" + error);
}
网友评论