avoid_catches_without_on_clauses
Avoid catches without on clauses.
Details
#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:
try {
somethingRisky()
} catch(e) {
doSomething(e);
}
GOOD:
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
, orFlutterError.reportError
, or any function with a return type ofNever
. - 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."
Enable
#To enable the avoid_catches_without_on_clauses
rule,
add avoid_catches_without_on_clauses
under linter > rules in your
analysis_options.yaml
file:
linter:
rules:
- avoid_catches_without_on_clauses
If you're instead using the YAML map syntax to configure linter rules,
add avoid_catches_without_on_clauses: true
under linter > rules:
linter:
rules:
avoid_catches_without_on_clauses: true
除非另有说明,文档之所提及适用于 Dart 3.7.0 版本,本页面最后更新时间: 2025-01-27。 查看文档源码 或者 报告页面问题。