【问题标题】:Using nested try-catch blocks使用嵌套的 try-catch 块
【发布时间】:2023-03-19 15:16:01
【问题描述】:

tl;dr 如果一个任务可能在多个事件中失败,例如API 获取、划分、解析等,是否有多个 try-catch 块或单个块来全部捕获


我有一个执行两项任务的函数。

  1. 从 API 中获取两个号码,ab
  2. 执行a/b

这是实际问题的简化版本。我想问一下如何处理异常,因为任务可能会在两个步骤中的任何一个上失败:

  1. 提取本身失败。
  2. a/b 导致错误,因为 b = 0

我可以想到两种方法。

选项一

try {
  const data = getFromAPI();
  const result = data[0] / data[1];
  return result;
} catch (err) {
  // Catch all errors here...
}

选项二

try {
  try {
     const data = getFromAPI();
  } catch(err) {
    // Catch all API errors here..
  }
  const result = data[0] / data[1];
  return result;
} catch (err) {
  // Catch division errors here...
}

【问题讨论】:

标签: javascript


【解决方案1】:

您应该首先检查您正在使用的数据(尽可能合理地)。之后,您应该只尝试/捕获可能失败的代码/当它超出您的控制时,仅此而已。所以我会给你另一个选择。 并且要回答您的其他问题,切勿使用嵌套的 try catch 语句。这根本没有意义。如果可能发生不同类型的异常,请尝试识别异常的类型(即使用错误对象的 instanceOf 方法或属性)并进行处理。

选项三

try {
  var data = getFromAPI();
} catch (err) {
  // Catch errors from the API request here...
}
if(Array.isArray(data) && !isNaN(data[0]) && !isNaN(data[1]) && data[0] > 0 && data[1] > 0) {
    const result = data[0] / data[1];
    return result;
}

return 0;

【讨论】:

  • 您的 if 块类似于 try-catch,您可以在其中返回 result0。它与使用另一个 try-catch 有何不同?换句话说,我们是否应该只在我们无法控制的事情可能失败时才使用try-catch
  • 是的,当它超出您的控制范围时,您可以使用 try catch 块。并使用 if else 来检查是否可以/应该执行某事,不要使用 try / catch as if / else 语句,这是一个非常糟糕的做法!
【解决方案2】:

这是一个问题,答案取决于系统,你是想告诉用户还是想知道抛出了什么样的异常而不是做几次 try/catch 建议你在内部使用 switch 或 if catch 而不是多个嵌套的 try/catch。

try{
  //your code
}catch(ex){
  if(ex instanceof ReferenceError){
    //handle error
  }
}

【讨论】:

    【解决方案3】:

    你可以简单地使用:

      try {
         const data = getFromAPI(); //wait for request to finish
    
         if(typeof data !== 'object') throw('fetch error');
    
         if(data[0] === 0 || 
            data[1] === 0 ||
            typeof data[0]!== 'number' ||
            typeof data[1]!== 'number' 
             ) throw('your error here');
    
          const result = data[0] / data[1]; 
          return result;
    
       } catch (err) {
      // Catch all errors here...
      }
    

    【讨论】:

    • 我这里没有async/await 问题。假设getFromAPI 处理所有这些。这里的 API 错误,我的意思更像是缺少 ab(一个或两个)。
    • 如果条件不匹配,你可以在 try 中抛出一个新的错误,这样你就不必使用多个 try-catch
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-30
    • 2022-01-01
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 2011-12-09
    相关资源
    最近更新 更多