function f(){
try{
if (/*some codes*/) throw false;
return true;
}
catch(x){
if (x===false) return false;
throw x;
}
}
这里,“throw x”是什么意思?似乎“catch”中的代码不会运行两次。
最佳答案
当您在 Javascript 中有一个 try/catch
块时,catch
块将承担 try
块中可能发生的任何错误。关键字 throw
用于向上级作用域(调用示例函数)抛出错误,并在其上传递错误(异常),该错误将由 catch
块处理。在 catch
中,您可以将异常作为第一个参数。在您的代码中,您使用 throw x
抛出错误,其中 x
是异常。调用者将获得 x
作为 catch 块上的参数。
function K()
{
try
{
f();
}
catch(ex)
{
// handle any exception thrown by f();
}
}
关于javascript - 如果我在 "throw"中使用 "catch"会怎样?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22069532/