Catch clause swallows the exception with no handling
ID |
scala.correctness.empty_catch_block |
Severity |
low |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Error Handling |
Language |
Scala |
Description
Reports a case clause in a catch block whose body is empty, so the exception it binds is discarded without being logged, rethrown or converted into a result.
Rationale
A silently swallowed exception turns a failure into a wrong answer: the code continues as if the operation had succeeded, and the only record of what went wrong - the exception and its stack trace - is thrown away. Faults surface far from their cause, and diagnosing them from a production log becomes guesswork.
The following code illustrates the pattern detected by this rule:
class EmptyCatchBlock {
def read(path: String): Unit = {
// FLAGGED: Catch clause swallows the exception with no handling
try {
println(path.length)
} catch {
case e: IOException =>
}
}
}
Remediation
Handle the failure: log the exception with its stack trace, rethrow it (possibly wrapped in a domain exception), or return a value that represents the failure, such as Try, Either or Option. If ignoring it really is correct, say so with a comment explaining why, so the next reader does not read the empty block as an unfinished edit.