throw 语句
生成一个可由 try...catch...finally 语句处理的错误条件。
throw [exception]
实参
- 异常
可选。 任何表达式。
备注
使用 throw 语句时可不带参数,但是只有在 throw 语句包含在 catch 块中时才可以这样做。 在这种情况下,throw 语句会再次引发由封闭 catch 语句捕获的错误。 提供参数时,throw 语句会引发 exception 的值。
示例
下面的示例基于传入的值引发一个错误,然后阐释了在 try...catch...finally 语句层次中如何处理该错误:
function ThrowDemo(x)
{
try
{
try
{
// Throw an exception that depends on the argument.
if (x == 0)
throw new Error(200, "x equals zero");
else
throw new Error(201, "x does not equal zero");
}
catch(e)
{
// Handle the exception.
switch (e.number)
{
case 200:
print (e.message + " - handled locally.");
break;
default:
// Throw the exception to a higher level.
throw e;
}
}
}
catch(e)
{
// Handle the higher-level exception.
print (e.message + " - handled higher up.");
}
}
ThrowDemo (0);
ThrowDemo (1);
// Output:
// x equals zero - handled locally.
// x does not equal zero - handled higher up.