javascript中 try catch finally 的使用 ( 转载 )
try...catch...finally 语句
为 JScript 实现错误处理。
try {
tryStatements}
catch(exception){
catchStatements}
finally {
finallyStatements}
=============
tryStatement
必选项。可能发生错误的语句。
exception
必选项。任何变量名。exception 的初始化值是扔出的错误的值。
catchStatement
可选项。处理在相关联的 tryStatement 中发生的错误的语句。
finallyStatements
可选项。在所有其他过程发生之后无条件执行的语句。
说明
try...catch...finally 语句提供了一种方法来处理可能发生在给定
tryStatements 参数包含可能发生错误的代码,而 catchStatement 则包含处理任何发生了的错误的代码。如果在 tryStatements 中发生了一个错误,则
如果在与发生错误的 tryStatements 相关联的 catchStatements 中不能处理该错误,则使用 throw 语句来传播、或重新扔出这个错误给更
在执行完 tryStatements 中的语句,并在 catchStatements 的所有错误处理发生之后,可无条件执行 finallyStatements 中的语句。
请注意,即使在 try 或 catch 块中返回一个语句,或在 catch 块重新扔出一个错误,仍然会执行 finallyStatements 编码。一般将确保 finallyStatments 的
示例
下面的例子阐明了JScript 特例处理是如何进行的。
try {
print("Outer try running..");
try {
print("Nested try running...");
throw "an error";
}
catch(e) {
print("Nested catch caught " + e);
throw e + " re-thrown";
}
finally {
print("Nested finally is running...");
}
}
catch(e) {
print("Outer catch caught " + e);
}
finally {
print("Outer finally running");
}
// Windows Script Host 作出该修改从而得出 WScript.Echo(s)
function print(s){
document.write(s);
}
将得出以下结果:
Outer try running..
Nested try running...
Nested catch caught an error
Nested finally is running...
Outer catch caught an error re-thrown
Outer finally running
如下是Javascript的例外处理的一个实例。
var array = null;
try {
document.write(array[0]);
} catch(err) {
document.writeln("Error name: " + err.name + "");
document.writeln("Error message: " + err.message);
}
finally{
alert("object is null");
}
程序执行过程
1. array[0]的时候由于没有创建array数组,array是个空对象,程序中调用array[0]就会产生object is null的异常
2. catch(err)语句捕获到这个异常通过err.name打印了错误类型,err.message打印了错误的详细信息.
3. finally类似于java的finally,无论有无异常都会执行.
现总结Error.name的六种值对应的信息:
1. EvalError:eval()的使用与定义不一致
2. RangeError:数值越界
3. ReferenceError:非法或不能识别的引用数值
4. SyntaxError:发生语法解析错误
5. TypeError:操作数类型错误
6. URIError:URI处理函数使用不当