Declaration of Catch for Generic Exception
Catching overly broad exceptions promotes complex error handling code that is more likely to contain security vulnerabilities.
Multiple catch blocks can get ugly and repetitive, but "condensing" catch blocks by catching a high-level class like Exception can obscure exceptions that deserve special treatment or that should not be caught at this point in the program. Catching an overly broad exception essentially defeats the purpose of Java's typed exceptions, and can become particularly dangerous if the program grows and begins to throw new types of exceptions. The new exception types will not receive any attention.
The following examples help to illustrate the nature of this weakness and describe methods or techniques which can be used to mitigate the risk.
Note that the examples here are by no means exhaustive and any given weakness may have many subtle varieties, each of which may require different detection methods or runtime controls.
The following code excerpt handles three types of exceptions in an identical fashion.
At first blush, it may seem preferable to deal with these exceptions in a single catch block, as follows:
However, if doExchange() is modified to throw a new type of exception that should be handled in some different kind of way, the broad catch block will prevent the compiler from pointing out the situation. Further, the new catch block will now also handle exceptions derived from RuntimeException such as ClassCastException, and NullPointerException, which is not the programmer's intent.
Weaknesses in this category are related to the CISQ Quality Measures for Security. Presence of these weaknesses could reduce the security of the software.
Weaknesses in this category are related to the CISQ Quality Measures for Reliability. Presence of these weaknesses could reduce the reliability of the software.
This category identifies Software Fault Patterns (SFPs) within the Ambiguous Exception Type cluster (SFP5).
This view (slice) covers all the elements in CWE.
This view (slice) lists weaknesses that can be introduced during implementation.
This view (slice) lists weaknesses that can be introduced during design.