版本

no-unsafe-finally

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

建議

設定檔中使用 @eslint/jsrecommended 設定會啟用此規則

JavaScript 會暫停 trycatch 區塊的控制流程語句,直到 finally 區塊執行完成。因此,當在 finally 中使用 returnthrowbreakcontinue 時,trycatch 內的控制流程語句會被覆寫,這被認為是不預期的行為。例如:

// 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
// We expect this function to throw an error, then return
(() => {
    try {
        throw new Error("Try"); // error is thrown but suspended until finally block ends
    } finally {
        return 3; // 3 is returned before the error is thrown, which we did not expect
    }
})();

// > 3
// We expect this function to throw Try(...) error from the catch block
(() => {
    try {
        throw new Error("Try")
    } catch(err) {
        throw err; // The error thrown from try block is caught and rethrown
    } finally {
        throw new Error("Finally"); // Finally(...) is thrown, which we did not expect
    }
})();

// > Uncaught Error: Finally(...)
// We expect this function to return 0 from try block.
(() => {
  label: try {
    return 0; // 0 is returned but suspended until finally block ends
  } finally {
    break label; // It breaks out the try-finally block, before 0 is returned.
  }
  return 1;
})();

// > 1

規則詳情

此規則禁止在 finally 區塊內使用 returnthrowbreakcontinue 語句。它允許間接使用,例如在 functionclass 定義中。

此規則的不正確程式碼範例

在線上測試中開啟
/*eslint no-unsafe-finally: "error"*/
let foo = function() {
    try {
        return 1;
    } catch(err) {
        return 2;
    } finally {
        return 3;
    }
};
在線上測試中開啟
/*eslint no-unsafe-finally: "error"*/
let foo = function() {
    try {
        return 1;
    } catch(err) {
        return 2;
    } finally {
        throw new Error;
    }
};

此規則的正確程式碼範例

在線上測試中開啟
/*eslint no-unsafe-finally: "error"*/
let foo = function() {
    try {
        return 1;
    } catch(err) {
        return 2;
    } finally {
        console.log("hola!");
    }
};
在線上測試中開啟
/*eslint no-unsafe-finally: "error"*/
let foo = function() {
    try {
        return 1;
    } catch(err) {
        return 2;
    } finally {
        let a = function() {
            return "hola!";
        }
    }
};
在線上測試中開啟
/*eslint no-unsafe-finally: "error"*/
let foo = function(a) {
    try {
        return 1;
    } catch(err) {
        return 2;
    } finally {
        switch(a) {
            case 1: {
                console.log("hola!")
                break;
            }
        }
    }
};

何時不該使用

如果您想要允許在 finally 區塊中使用控制流程操作,您可以關閉此規則。

版本

此規則在 ESLint v2.9.0 中引入。

資源

變更語言