第十章 错误处理
10.1 try…catch语句
JavaScript中的错误可以用try…catch语句捕获。
语法如下:
try{
//normalcode
}
catch(Exception对象的变量名)
{
//codeafter exception happened
}
}
示例如下:
try{
document.write("errorbegins"+a);
}
catch(ex)
{
if(ex.description)
{
alert(ex.number+ "\r\n"+ex.description);
}
else
{
alert(ex.name+ "\r\n"+ex.message);
}
}
运行网页,在Google Chrome中将弹出分两行显示“ReferenceError”和“a is not defined”对话框。
此处需要注意,不同的浏览器对错误Exception对象提供的属性不同。IE,Google提供的是name(错误名称)和message(错误描述),而Firefox中提供的是Number(错误ID号)和decription(对应IE的message)。我们可以根据是否存在某属性来进行处理此浏览器之间的差别。
10.2 throw语句
我们也可以人为的利用throw语句抛出错误。语法如下:
throwexceptionobject
此处的exceptionobject可以为任意对象,字符串,数组或者数字都可以。此时catch到的Exception对象就是此处的exceptionobject。
比如:
try{
throw"catch me";
}
catch(ex)
{
alert(ex);
}
将弹出catch me的对话框。
10.3 finally语句
不管有无错误,finally语句块中的代码都会被执行。示例如下:
try{
throw"catch me";
}
catch(ex)
{
alert(ex);
}
finally
{
alert(“codein finally block”);
}
代码将先后弹出“catch me”“和”code in finally block“对话框。