CWE-396: Declaration of Catch for Generic Exception
Description
Catching overly broad exceptions promotes complex error handling code that is more likely to contain security vulnerabilities.
Submission Date :
July 19, 2006, midnight
Modification Date :
2023-06-29 00:00:00+00:00
Organization :
MITRE
Extended 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.
Example - 1
The following code excerpt handles three types of exceptions in an identical fashion.
doExchange();
logger.error("doExchange failed", e);
logger.error("doExchange failed", e);
logger.error("doExchange failed", e);try {}catch (IOException e) {}catch (InvocationTargetException e) {}catch (SQLException e) {}
At first blush, it may seem preferable to deal with these exceptions in a single catch block, as follows:
doExchange();
logger.error("doExchange failed", e);try {}catch (Exception e) {}
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.
Related Weaknesses
This table shows the weaknesses and high level categories that are related to this weakness. These relationships are defined to give an overview of the different insight to similar items that may exist at higher and lower levels of abstraction.
Visit http://cwe.mitre.org/ for more details.