跳至內容

eslint/no-unsafe-finally 正確性

此規則預設為開啟。

作用

禁止在 finally 區塊中使用控制流程語句

為什麼這是不好的?

JavaScript 會暫停 try 和 catch 區塊的控制流程語句,直到 finally 區塊執行完成。因此,當在 finally 中使用 return、throw、break 或 continue 時,try 和 catch 內的控制流程語句會被覆蓋,這被認為是意料之外的行為。

範例

javascript
// We expect this function to return 1;
(() => {
  try {
    return 1; // 1 is returned but suspended until finally block ends
  } catch (err) {
    return 2;
  } finally {
    return 3; // 3 is returned before 1, which we did not expect
  }
})();

// > 3

參考資料

根據 MIT 許可證發布。