Catch clause handles Error, which signals a programming bug
ID |
dart.correctness.avoid_catching_errors |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
medium |
Resource |
Error Handling |
Language |
Dart |
Description
Reports on clauses that catch Error or one of its subclasses, such as StateError, RangeError, AssertionError or TypeError.
Rationale
Dart splits throwables in two on purpose: Exception covers conditions a program is expected to recover from, while Error marks a contract the code itself has broken — an index out of range, a null check that failed, an assertion that did not hold. Catching an Error therefore does not recover from anything; it hides the bug, lets execution continue over the state that produced it, and moves the eventual failure somewhere unrelated. The stack trace that pointed at the real defect is discarded with it.
The following code illustrates the pattern detected by this rule:
class Repository {
int lookup(List<int> rows, int index) {
// FLAGGED: Catch clause handles Error, which signals a programming bug
try {
return rows[index];
} on RangeError catch (e) {
report(e);
return -1;
}
}
void commit() {}
void apply(String raw) {}
void report(Object e) {}
}
Remediation
Remove the handler and fix the precondition that raises the Error: check bounds before indexing, validate arguments at the boundary, guard the state before the call. When the value genuinely comes from outside the program, convert it at the edge and throw an Exception subclass the caller can handle instead.