0

tl;drtry-catch如果一个任务可能在多个事件中失败,例如 API 获取、划分、解析等,那么使用多个块或一个块来捕获它们是否有意义?


我有一个执行两项任务的功能。

  1. 从 API 中获取两个数字,a然后b.
  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...
}
4

3 回答 3

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;
于 2019-10-14T16:57:07.080 回答
0

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

try{
  //your code
}catch(ex){
  if(ex instanceof ReferenceError){
    //handle error
  }
}
于 2019-10-14T16:52:22.847 回答
0

你可以简单地使用:

  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...
  }
于 2019-10-14T17:03:32.210 回答