Details
-
Type:
Code Smell Detection
-
Status: Active
-
Resolution: Unresolved
-
Labels:
-
Message:Catch a list of specific exception subtypes instead.
-
Default Severity:Minor
-
Impact:Low
-
Likelihood:Low
-
Legacy Key:WhenOthersAsOnlyExceptionHandlerCheck
-
Covered Languages:C#, Java, PL/SQL
-
Remediation Function:Constant/Issue
-
Constant Cost:15min
-
Analysis Scope:Main Sources
-
CWE:CWE-396
-
Checkstyle:IllegalCatch
-
FindBugs:REC_CATCH_EXCEPTION
-
FxCop:DoNotCatchGeneralExceptionTypes, CA1031
-
PMD:AvoidCatchingGenericException
Description
Catching Exception seems like an efficient way to handle multiple possible exceptions. Unfortunately, it traps all exception types, both checked and runtime exceptions, thereby casting too broad a net. Indeed, was it really the intention of developers to also catch runtime exceptions? To prevent any misunderstanding, if both checked and runtime exceptions are really expected to be caught, they should be explicitly listed in the catch clause.
This rule raises an issue if Exception is caught when it is not explicitly thrown by a method in the try block.
Noncompliant Code Example
try { // do something that might throw an UnsupportedDataTypeException or UnsupportedEncodingException } catch (Exception e) { // Noncompliant // log exception ... }
Compliant Solution
try { // do something } catch (UnsupportedEncodingException|UnsupportedDataTypeException|RuntimeException e) { // log exception ... }
or if runtime exceptions should not be caught:
try { // do something } catch (UnsupportedEncodingException|UnsupportedDataTypeException e) { // log exception ... }
See
- MITRE, CWE-396 - Declaration of Catch for Generic Exception
Attachments
Issue Links
- is implemented by
-
SONARJAVA-1253 Rule S2221: "Exception" should not be caught when not required by called methods
-
- Closed
-
- is related to
-
SONARJAVA-1554 FP on S2221: invocation of unknown methods should not raise issue
-
- Closed
-
-
RSPEC-2738 General "catch" clauses should not be used
- Active
1.
|
PL/SQL: "WHEN OTHERS" should not be the only exception handler | RSPEC-2571 |
|
Active | Unassigned | |
2.
|
C# | RSPEC-4044 |
|
Active | Unassigned |