了解 JavaScript 中的异常处理:当更改 try/catch 块的位置时,获得不同的输出
understanding exception handling in JavaScript: get different output when changed the place of try/catch block
我是学习JavaScript的新手,在学习异常处理时有点卡住了。我已经了解每当发生异常时,它都会使用"throw"关键字抛出,同样地,它也会使用"catch"块捕获。
但是我无法理解的是,我有一个小而简单的代码来演示简单的异常处理技术,并且在该代码中,每当我更改 catch 块的位置时,我都会得到不同的输出。这是简单的代码及其不同的 o/p s,具体取决于我放置 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."
捕获块中的"出现问题"未打印。
为什么会这样??同样,当我将try/catch块放在不同的代码段周围时(例如:围绕第一个函数,最后一个元素加十函数的主体等)我得到不同的 o/p s. 为什么会这样。异常处理如何工作?
问题是你把try/catch放在函数声明周围——错误不是在那里抛出的,而是在实际调用函数时抛出的。 所以你需要这个:
// this code block will not throw any error, although it will when the function is invoked
function lastElementPlusTen(array) {
return lastElement(array) + 10;
}
try{
console.log(lastElementPlusTen([]));
}
catch (error) {
console.log("Something went wrong: ", error);
}
小提琴演示
在第二种情况下,您没有捕获异常。它只是抛出未经处理的异常,没有按预期打印它,放置
print(lastElementPlusTen([]));
里面试试..抓住
尝试:
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 { //<-- this is where you need try.. catch not at the function definision
print(lastElementPlusTen([])); //<-- this invokes the error.
} catch (error) {
print("Something went wrong: ", error);
}
演示 观看控制台以获取日志
相关文章:
- 在输出数字的千分之一位置插入逗号
- 使用Gulp Usemin将JS和HTML输出到不同的位置
- 为多个表单动态指定输出ajax成功结果的位置
- 在事件发生时获取元素位置的当前页面 URL,并将该 URL 输出到另一个页面上
- 合并位置并从 JSON 输出组合数据
- 将显示为 XML 格式的 Google 地图位置转换为输出 (ASP.Net、C#)
- 了解 JavaScript 中的异常处理:当更改 try/catch 块的位置时,获得不同的输出
- 将显示与位置绝对输出移动的表单放入移动模式引导按钮中
- 在控制台上输出滚动位置
- 如何在单击位置旁边输出文本
- Box2dWeb中是否有方法将对象的位置.x输出到console.log()
- 影响输出的功能的位置
- Live Validation更改输出位置
- 循环对象,根据位置输出不同的html
- D3.js multigraph:在x轴上输出滑块值的相对Y值,并与SVG点位置匹配
- 改变数组输出的Y位置
- 您可以更改随机生成的html文件的输出位置吗?
- 函数getelementbyid没有输出到正确的位置
- 获取选定单元格在Google工作表中的位置,并输出到另一个单元格
- 使用jQuery将PHP函数的结果输出到特定的HTML位置