目录

avoid_catches_without_on_clauses

Avoid catches without on clauses.

此规则自 Dart 2.0 版本起可用。

详情

#

From Effective Dart:

AVOID catches without on clauses.

Using catch clauses without on clauses make your code prone to encountering unexpected errors that won't be thrown (and thus will go unnoticed).

BAD:

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

GOOD:

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

A few exceptional cases are allowed:

  • If the body of the catch rethrows the exception.
  • If the caught exception is "directly used" in an argument to Future.error, Completer.completeError, or FlutterError.reportError, or any function with a return type of Never.
  • If the caught exception is "directly used" in a new throw-expression.

In these cases, "directly used" means that the exception is referenced within the relevant code (like within an argument). If the exception variable is referenced before the relevant code, for example to instantiate a wrapper exception, the variable is not "directly used."

使用方法

#

要启用 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