理解JavaScript中的异常处理:更改try/catch块的位置时获得不同的输出

理解JavaScript中的异常处理:更改try/catch块的位置时获得不同的输出,javascript,exception-handling,try-catch,Javascript,Exception Handling,Try Catch,我对学习JavaScript还不熟悉,在学习异常处理时有点自以为是。 我已经理解了每当异常发生时,都会使用“throw”关键字抛出异常,类似地,也会使用“catch”块捕获异常 但我无法理解的是,我有一个小而简单的代码,它演示了简单的异常处理技术,在这段代码中,每当我更改catch块的位置时,我都会得到不同的输出。下面是简单代码及其不同的o/p,具体取决于我放置捕捉块的位置 function lastElement(array) { if (array.length > 0)

我对学习JavaScript还不熟悉,在学习异常处理时有点自以为是。 我已经理解了每当异常发生时,都会使用“throw”关键字抛出异常,类似地,也会使用“catch”块捕获异常

但我无法理解的是,我有一个小而简单的代码,它演示了简单的异常处理技术,在这段代码中,每当我更改catch块的位置时,我都会得到不同的输出。下面是简单代码及其不同的o/p,具体取决于我放置捕捉块的位置

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块放在不同的代码段周围时
(例如:关于第一个函数,最后一个元素的主体,plusten函数等等)我得到了不同的o/p。为什么会发生这种情况。异常处理是如何工作的???

在第二种情况下,您没有捕获到异常。它只是抛出未经处理的异常,而不是按预期的方式打印它

print(lastElementPlusTen([]));
内试

尝试:

函数lastElement(数组){
如果(array.length>0)返回数组[array.length-1];
else抛出“不能获取空数组的最后一个元素。”;
}
函数lastElementPlusTen(数组){
返回lastElement(数组)+10;
}

try{/问题在于,您将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);
}

您使用的是什么JavaScript环境?我只是想知道它似乎不是一个浏览器环境。是的!我在学习“雄辩的JavaScript”,所以我使用他们提供的控制台
// 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);
}