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

understanding exception handling in JavaScript: get different output when changed the place of try/catch block

本文关键字:位置 输出 catch 异常处理 JavaScript try 了解      更新时间:2023-09-26

我是学习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);
}

演示 观看控制台以获取日志