Catch clause takes the generic Exception type
ID |
apex.correctness.catch_specific_exception |
Severity |
high |
Remediation Complexity |
medium |
Remediation Risk |
medium |
Remediation Effort |
medium |
Resource |
Error Handling |
Language |
Apex |
Description
Reports a catch clause declared on Exception rather than on the specific exception the guarded code can throw. A handler that rethrows - the outermost translation to an AuraHandledException, for instance - is not reported.
Rationale
catch (Exception e) absorbs everything, including the failures the handler was not written for: a NullPointerException from a typo, a LimitException that means the transaction is over its governor budget, a QueryException from a query that returned no rows. The handler then reports its one intended story - "could not save the record" - for a defect that is nothing of the kind, and the real cause is gone. Catching LimitException in particular hides the one failure that must not be swallowed, because the transaction cannot continue.
The following code illustrates the pattern detected by this rule:
public class CatchTypes {
public void save(Account a) {
// FLAGGED: Catch clause takes the generic Exception type
try {
insert a;
} catch (Exception e) {
System.debug(LoggingLevel.ERROR, e);
}
}
@AuraEnabled
public static Account load(Id recordId) {
try {
return [SELECT Id, Name FROM Account WHERE Id = :recordId];
} catch (Exception e) {
throw new AuraHandledException(e.getMessage());
}
}
public void saveSpecific(Account a) {
try {
insert a;
} catch (DmlException e) {
System.debug(LoggingLevel.ERROR, e);
}
}
}