【问题标题】:Javascript error handling with try .. catch .. finally使用 try .. catch .. finally 处理 Javascript 错误
【发布时间】:2008-11-13 05:01:39
【问题描述】:

我怀疑我错误地使用了 finally 块,并且我不了解其用途的基本原理...

 function myFunc() {
      try {
           if (true) {
                throw "An error";
           }
      } catch (e) {
           alert (e);
           return false;
      } finally {
           return true;
      }
 }

此函数将运行catch 块,警告“错误”,但随后返回true。为什么不返回 false?

【问题讨论】:

    标签: javascript error-handling finally


    【解决方案1】:

    finally 块包含要在 try 和 catch 块执行之后但在 try...catch 语句之后的语句之前执行的语句。无论是否抛出异常,finally 块都会执行。如果抛出异常,即使没有 catch 块处理异常,finally 块中的语句也会执行。 more

    finally 块将始终运行,尝试在您的 try 块之后返回 true

    function myFunc() {
         try {
             if (true) {
                   throw "An error";
              }
              return true;
         } catch (e) {
              alert (e);
              return false;
         } finally {
              //do cleanup, etc here
         }
     }
    

    【讨论】:

      【解决方案2】:

      当您离开 try 块时,最终块会执行。在您的代码中,当您返回 false 时会发生这种情况。这会将返回值设置为 false 并尝试退出该函数。但首先它必须退出触发 finally 的 try 块并将返回值覆盖为 true。

      许多人认为每个函数都有一个返回语句是一种很好的编程习惯。考虑在函数的开头创建一个 var retval,并在整个函数中根据需要将其设置为 true 或 false,然后构建代码以使其正确地落入底部的单个 return。

      【讨论】:

      • 使用单个返回值是解决简化函数意图和清晰度问题的一种有效且有用的策略。使用变量来存储返回值也是解决复杂返回值逻辑的有效手段。但是,我不认为可以说函数中的多个 return 语句自动成为不良编程习惯的标志。在许多情况下,这很好:代码的编写更简单,并且可以清楚地将函数的意图传达给需要理解它的下一个程序员。 function a(i) {if (i===undefined) {return;} ...}
      • 顶部的返回语句非常清楚。没有必要强制整个函数位于 if 块内。
      【解决方案3】:
      function getTheFinallyBlockPoint(someValue) {
          var result;
          try {
              if (someValue === 1) {
                  throw new Error("Don't you know that '1' is not an option here?");
              }
              result = someValue
          } catch (e) {
              console.log(e.toString());
              throw e;
          } finally {
              console.log("I'll write this no matter what!!!");
          }
      
          return result;
      };
      
      getTheFinallyBlockPoint("I wrote this only because 'someValue' was not 1!!!");
      getTheFinallyBlockPoint(1);
      

      在浏览器的控制台上运行它,它可能会给你想要的答案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-03-27
        • 1970-01-01
        • 2020-08-17
        • 1970-01-01
        • 2017-09-14
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多