跳到主要内容

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