【问题标题】:understanding exception handling in JavaScript: get different output when changed the place of try/catch block理解 JavaScript 中的异常处理:更改 try/catch 块的位置时获得不同的输出
【发布时间】: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


【解决方案1】:

在第二种情况下,您没有发现异常。它只是抛出未处理的异常,而不是按预期打印,放置

print(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.";
}

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);
}

Demo查看控制台的日志

【讨论】:

    【解决方案2】:

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

    Fiddle demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-01
      • 2011-04-01
      • 2018-12-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多