Catch block swallows the exception
ID |
apex.correctness.empty_catch_block |
Severity |
high |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Error Handling |
Language |
Apex |
Description
Reports a catch clause with an empty body, which discards the exception and lets execution continue as if nothing had failed.
Rationale
In Apex the swallowed exception is usually a DML or a query failure, so the transaction carries on with records that were not saved and a user sees a success screen. Nothing reaches the debug log either, because the platform only logs what is thrown out of the transaction - so the failure leaves no trace anywhere, and the report of "the record did not update" arrives days later with nothing to investigate.
The following code illustrates the pattern detected by this rule:
public class ErrorHandling {
public void save(Account a) {
// FLAGGED: Catch block swallows the exception
try {
insert a;
} catch (DmlException e) {
}
}
public void saveLogged(Account a) {
try {
insert a;
} catch (DmlException e) {
System.debug(LoggingLevel.ERROR, e);
a.addError(Label.Save_Failed);
}
}
}
Remediation
Handle the exception, or at minimum log it with System.debug(LoggingLevel.ERROR, e) and add the error to the record with addError so the user sees it. Where the failure really is expected and harmless, say so in a comment and keep the logging: an empty body cannot be told from a forgotten one.