Declaration of Catch for Generic Exception
Catching overly broad exceptions promotes complex error handling code that is more likely to contain security vulnerabilities.
Description
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 a language'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.
Demonstrations
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.
Example One
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.
See Also
Weaknesses in this category are related to insufficient control flow management.
Weaknesses in this category are related to the CISQ Quality Measures for Security, as documented in 2016 with the Automated Source Code Security Measure (ASCSM) Specif...
Weaknesses in this category are related to the CISQ Quality Measures for Reliability, as documented in 2016 with the Automated Source Code CISQ Reliability Measure (AS...
This view (slice) covers all the elements in CWE.
This view (slice) lists weaknesses that can be introduced during implementation.
This view (slice) displays only weakness base elements.
Common Weakness Enumeration content on this website is copyright of The MITRE Corporation unless otherwise specified. Use of the Common Weakness Enumeration and the associated references on this website are subject to the Terms of Use as specified by The MITRE Corporation.