跳到主要內容

avoid_catches_without_on_clauses

穩定

避免使用沒有 on 子句的 catch。

詳情

#

來自 Effective Dart

避免使用沒有 on 子句的 catch。

使用沒有 on 子句的 catch 子句會使你的程式碼容易遇到不會被丟擲(因此會被忽視)的意外錯誤。

不好

dart
try {
 somethingRisky()
} catch(e) {
  doSomething(e);
}

dart
try {
 somethingRisky()
} on Exception catch(e) {
  doSomething(e);
}

允許少數例外情況

  • 如果 catch 的主體重新丟擲異常。
  • 如果在 Future.errorCompleter.completeErrorFlutterError.reportError 的引數中“直接使用”了捕獲的異常,或在任何返回型別為 Never 的函式中“直接使用”了捕獲的異常。
  • 如果在新的 throw 表示式中“直接使用”了捕獲的異常。

在這些情況下,“直接使用”意味著異常在相關程式碼中被引用(例如在引數中)。如果異常變數在相關程式碼之前被引用,例如為了例項化一個包裝異常,則該變數不是“直接使用”。

啟用

#

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

analysis_options.yaml
yaml
linter:
  rules:
    - avoid_catches_without_on_clauses

如果你使用的是 YAML map 語法來配置 linter 規則,請在 linter > rules 下新增 avoid_catches_without_on_clauses: true

analysis_options.yaml
yaml
linter:
  rules:
    avoid_catches_without_on_clauses: true