【问题标题】:Can you specify a try handler without a catch or finally block in ES?你能在 ES 中指定一个没有 catch 或 finally 块的 try 处理程序吗?
【发布时间】:2019-05-17 00:53:39
【问题描述】:

有没有办法在 JavaScript 中定义一个没有 catch 的 try 块?

编译器报错如下代码:

try {
    const newAPI = require("applicationutils");
}

仅供参考 每月都会推出新的 API。就我而言,如果 API 可用,我想采取新的行动。如果它们不可用,我将使用默认设置。我不需要 catch 块。我只是想知道这是否可能。

如果类不存在,代码会抛出错误,因此必须将其包装在 catch 块中。

【问题讨论】:

    标签: javascript ecmascript-6 try-catch


    【解决方案1】:

    如果没有catch 和/或finally,则无法使用try。根据MDN try...catch

    try 语句由一个 try 块组成,其中包含一个或多个 陈述。 {} 必须始终使用,即使对于单个语句也是如此。在 必须存在至少一个 catch 子句或 finally 子句。这个 为try 声明提供了三种形式:

    try...catch
    try...finally
    try...catch...finally
    

    【讨论】:

      【解决方案2】:

      您可以执行如下所示的操作,其中“块范围”在您的函数体中内联定义,从而有效地满足您的要求。

      这些由{ .. } 直接在您的函数中定义,并将词法/变量范围的新部分引入您的函数,例如,可以定义一个只能在该块范围内访问的变量。

      可以从这些内联块范围内抛出异常,并将被在调用堆栈中先前点定义的catch 处理程序捕获:

      function foo() {
          /* Start a block scope in function foo() */
          {
              /* newAPI only accessible in this block scope */
              const newAPI = require("applicationutils");
          }
      
          /* Start another block scope, defined in same function foo() */
          {           
              /* newAPI is unique to this block, the newAPI variable name
                 can be re-used seeing it's unique in the lexical scope */
              const newAPI = { getUsers : () => [] };
      
             /* Throwing an exception from block scope is okay - it does not
                need to be handled with a catch() clause on this block, and
                will be handled by an optional catch() clause lower in the 
                call stack */
             throw new Error('throwing from second block scope in foo()');
          }
          /* no catch(..) {} clause is syntactically required */
      }
      

      【讨论】:

      • 你能详细说明吗?
      • @1.21gigawatts 是的,当然可以 - 请参阅更新的答案。希望有帮助:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-01
      • 2014-11-27
      • 2012-03-06
      • 2011-08-31
      • 2017-09-14
      • 2015-09-05
      • 2020-08-24
      相关资源
      最近更新 更多