跳到主要內容

throw_in_finally

穩定

避免在 finally 區塊中使用 throw

詳細資訊

#

避免finally 區塊中拋出例外。

finally 區塊中拋出例外,將不可避免地導致難以除錯的非預期行為。

錯誤範例

dart
class BadThrow {
  double nonCompliantMethod() {
    try {
      print('hello world! ${1 / 0}');
    } catch (e) {
      print(e);
    } finally {
      throw 'Find the hidden error :P'; // LINT
    }
  }
}

正確範例

dart
class Ok {
  double compliantMethod() {
    var i = 5;
    try {
      i = 1 / 0;
    } catch (e) {
      print(e); // OK
    }
    return i;
  }
}

啟用

#

若要啟用 throw_in_finally 規則,請在您的 analysis_options.yaml 檔案中的 linter > rules 下新增 throw_in_finally

analysis_options.yaml
yaml
linter:
  rules:
    - throw_in_finally

如果您改為使用 YAML map 語法來設定 linter 規則,請在 linter > rules 下新增 throw_in_finally: true

analysis_options.yaml
yaml
linter:
  rules:
    throw_in_finally: true