将测试进行到底!

捕捉异常 try...catch...finally 语句

上一篇 / 下一篇  2008-05-15 16:55:47 / 个人分类:load runner使用技术

为 Jscrīpt 实现错误处理。

try {
   tryStatements}
catch(exception){
   catchStatements}
finally {
  finallyStatements}

参数

tryStatement

必选项。可能发生错误的语句。

exception

可选项。任何变量名。exception的初始化值是扔出的错误的值。

catchStatement

可选项。处理在相关联的tryStatement中发生的错误的语句。

finallyStatements

可选项。在所有其他过程发生之后无条件执行的语句。

说明

try...catch...finally语句提供了一种方法来处理可能发生在给定代码块中的某些或全部错误,同时仍保持代码的运行。如果发生了程序员没有处理的错误,Jscrīpt 只给用户提供它的普通错误消息,就好象没有错误处理一样。

tryStatements参数包含可能发生错误的代码,而catchStatement则包含处理任何发生了的错误的代码。如果在tryStatements中发生了一个错误,则程序控制被传给catchStatements来处理。exception的初始化值是发生在tryStatements中的错误的值。如果错误不发生,则不执行catchStatements

如果在与发生错误的tryStatements相关联的catchStatements中不能处理该错误,则使用throw语句来传播、或重新扔出这个错误给更高级的错误处理程序。

在执行完tryStatements中的语句,并在catchStatements的所有错误处理发生之后,可无条件执行finallyStatements中的语句。

请注意,即使在trycatch块中返回一个语句,或在catch块重新扔出一个错误,仍然会执行finallyStatements编码。 一般将确保finallyStatments的运行,除非存在未处理的错误。(例如,在catch块中发生运行时错误。)。

示例

下面的例子阐明了Jscrīpt 特例处理是如何进行的。

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 scrīpt Host作出该修改从而得出Wscrīpt.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

TAG:

 

评分:0

我来说两句

Open Toolbar