簡體   English   中英

使用嵌套的 try-catch 塊

[英]Using nested try-catch blocks

tl;dr如果一個任務可能在多個事件中失敗,例如 API 獲取、除法、解析等,是否有多個try-catch塊或單個塊來捕獲它們


我有一個 function 在其中執行兩項任務。

  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...
}

您應該從檢查您正在使用的數據開始(盡可能合理地)。 之后,您應該只嘗試/捕獲可能失敗的代碼/當它超出您的控制時,僅此而已。 所以我會給你另一個選擇。 並且要回答您的其他問題,切勿使用嵌套的 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;

這是一個問題,答案取決於系統,你是想告訴用戶還是想知道拋出了什么樣的異常而不是做幾次 try / catch 建議你在 catch 中使用 switch 或 if 而不是多個嵌套的 try/catch。

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

你可以簡單地使用:

  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...
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM