【发布时间】:2013-11-02 12:33:11
【问题描述】:
我是学习 JavaScript 的新手,在学习异常处理时有点卡住。 我已经理解,每当发生异常时,都会使用“throw”关键字将其抛出,同样使用“catch”块将其捕获。
但我无法理解的是,我有一个小而简单的代码来演示简单的异常处理技术,并且在该代码中,每当我更改 catch 块的位置时,我都会得到不同的输出。这是简单的代码及其不同的 o/p,具体取决于我放置 catch 块的位置。
function lastElement(array) {
if (array.length > 0)
return array[array.length - 1];
else
throw "Can not take the last element of an empty array.";
}
function lastElementPlusTen(array) {
return lastElement(array) + 10;
}
try {
print(lastElementPlusTen([]));
}
catch (error) {
print("Something went wrong: ", error);
}
我在这里得到的 o/p 符合预期:
Something went wrong: Can not take the last element of an empty array.
现在当我在函数 lastElementPlusTen 周围添加 try/catch 块时:像这样
function lastElement(array) {
if (array.length > 0)
return array[array.length - 1];
else
throw "Can not take the last element of an empty array.";
}
try {
function lastElementPlusTen(array) {
return lastElement(array) + 10;
}
}
catch (error) {
print("Something went wrong: ", error);
}
print(lastElementPlusTen([]));
现在我得到的 o/p 是:
Exception: "Can not take the last element of an empty array."
catch 块中的“出现问题”没有打印出来。
为什么会这样??类似地,当我将 try/catch 块放置在不同的代码段周围时 (例如:围绕第一个函数,lastElementPlusTen 函数的主体等)我得到不同的 o/p 。为什么会这样。异常处理是如何工作的??
【问题讨论】:
-
您使用的是什么 JavaScript 环境?我只是想知道它似乎不是浏览器环境。
-
是的!我正在学习“雄辩的 javascript”,所以我正在使用他们提供的控制台
标签: javascript exception-handling try-catch