js中的异常处理
js中的异常处理语句有两个,一个是try……catch……,一个是throw。try……catch用于语法错误,错误有name和message两个属性。throw用于逻辑错误。对于逻辑错误,js是不会抛出异常的,也就是说,用try catch没有用。这种时候,需要自己创建error对象的实例,然后用throw抛出异常。
(1)try……catch……的普通使用
错误内容:charAt()小写了
try{ var str="0123"; console.log(str.charat(2)); }catch(exception){ console.log("name属性-->"+exception.name);//name属性-->TypeError console.log("message属性-->"+exception.message);//message属性-->str.charat is not a function }
(2)try……catch……无法捕捉到逻辑错误
错误内容:除数不能为0
try {
var num=1/0;
console.log(num);//Infinity
}catch(exception){
console.log(exception.message);
}
(3)用throw抛出异常,需要自己现实例化一个error
注意:throw要用new关键字初始化一个Error,E要大写。同时,这个Error是异常里面的message属性!
try{
var num=1/0;
if(num=Infinity){
throw new Error("Error大写,用new初始化-->除数不能为0");
}
}
catch(exception){
console.log(exception.message);
}本文内容仅供个人学习、研究或参考使用,不构成任何形式的决策建议、专业指导或法律依据。未经授权,禁止任何单位或个人以商业售卖、虚假宣传、侵权传播等非学习研究目的使用本文内容。如需分享或转载,请保留原文来源信息,不得篡改、删减内容或侵犯相关权益。感谢您的理解与支持!