Catch clause without an on clause catches every thrown object
ID |
dart.correctness.avoid_catches_without_on |
Severity |
low |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Error Handling |
Language |
Dart |
Description
Reports catch clauses written without an on clause, which intercept every object thrown inside the try body regardless of its type.
Rationale
A bare catch also swallows the throwables that signal a bug in the program rather than a recoverable runtime condition: AssertionError, TypeError, StackOverflowError and OutOfMemoryError all arrive at the same handler as the I/O or parsing failure the code was written for. The handler then applies its recovery path to a corrupted program state, so the defect surfaces far from its cause, and the diagnostic that would have pointed at it is gone.
The following code illustrates the pattern detected by this rule:
class Loader {
Map<String, dynamic> parse(String raw) {
// FLAGGED: Catch clause without an on clause catches every thrown object
try {
return jsonDecode(raw) as Map<String, dynamic>;
} catch (e) {
return const {};
}
}
void write(String raw) {}
void close() {}
void report(Object e, StackTrace? s) {}
}
Remediation
Name the exception the block can actually recover from with an on clause, for example on FormatException catch (e). When several failures need handling, write one on clause per type. If a broad handler really is required at a process or isolate boundary, keep it and rethrow anything it cannot handle.