1.使用window.onerror指定错误处理函数。
当有错误的时候,onerror会被callback。 当某个javascript block中有多个script错误时,第一个错误触发后(回调callback),当前javascript block后面的script会被自动drop忽略掉,不被执行。
如:
复制代码 代码如下:
test
在上面的例子中只会有每一个block中的第一个test();产生error。触发window.onerror回调,后面的javascript会被忽略掉。img 也支持 onerror 。onerror 是浏览器支持的对象。由浏览器决定是否可以使用,不是dom标准。
2.使用javascript中的try catch throw处理异常。
javascript支持了try catch throw,javascript中定义的异常:
(1)evalerror: an error occurs in the eval() function.
(2)rangeerror: a number value is greater then or less then the number that can be represented in javascript(number.max_value and number.min_vakue).
(3)referenceerror: an illegal reference is used.
(4)syntaxerror: a syntax error occus inside of an eval() function call. all other syntax error are reorted by the browser and cannot be handled with a try...catch statement.
(5)typeerror. a variables type is unexpected. 6.urierror. an error ocuurs in the encodeuri() or the decodeuri() function.
如:
复制代码 代码如下:
error.message是ie和firefox都支持的属性。
ie支持description 和 number属性。
ff支持filename linenumber 和 stack 属性。
由于javascript是弱类型的语言。
所以在catch部分只能catch一次,不能像c#这样的语言可以写多个catch,catch不同类型的exception。
但是可以用 instanceof errortype的方式实现类似的功能。
如:
复制代码 代码如下:
注:浏览器不会抛出error类型的exception异常,所以如果捕获到error类型的异常,可以确定这个异常是用户代码抛出的,不是浏览器抛出的。
javascript的assert()
复制代码 代码如下:
function assert(bcondition, serrormsg) {
if (!bcondition) {
alert(serrormsg);
throw new error(serrormsg);
}
}