七、错误处理
1.“JavaScript有一个标准的Error
对象表示错误,还有从Error
派生的TypeError
、ReferenceError
等错误对象。我们在处理错误时,可以通过catch(e)
捕获的变量e
访问错误对象:”
try {
...
} catch (e) {
if (e instanceof TypeError) {
alert('Type error!');
} else if (e instanceof Error) {
alert(e.message);
} else {
alert('Error: ' + e);
}
}
2.throw new Error('输入错误');
抛出Error对象并且会被catch语句捕获,“JavaScript允许抛出任意对象,包括数字、字符串,但最好还是抛出一个Error对象,并且用catch捕获错误时,一定要编写错误处理语句,但也不要用alert()
把错误显示给用户,可以在控制台打印错误信息。”
3.“不必在每一个函数内部捕获错误,因为如果当前函数没有错误处理语句,则错误会抛出到外层调用函数,只需要在合适的地方统一捕获并处理即可。”
4.“无法在调用异步代码时捕获(回调函数中的)错误,因为在捕获的当时,回调函数并未执行”,以下代码中,因为无法捕捉回调函数printTIme()
中的错误,所以无法打印得到error
。
function printTime() {
throw new Error();
}
try {
setTimeout(printTime, 1000);
console.log('done');
} catch (e) {
console.log('error');
}
“处理一个事件时,在绑定事件的代码处,无法捕获事件处理函数的错误”
5.练习,针对以下表单,捕获事件处理函数的错误:
<form>
<input id="x"> + <input id="y">
<button id="calc" type="button">计算</button>
</form>
'use strict';
var $btn = $('#calc');
// 取消已绑定的事件:
$btn.off('click');
$btn.click(function () {
try{
var
x = parseFloat($('#x').val()),
y = parseFloat($('#y').val()),
r;
if (isNaN(x) || isNaN(y)) {
throw new Error('输入有误');
}
r = x + y;
alert('计算结果:' + r);
}catch(e){
alert('输入有误!');
}
});