Rule Definition
Directly catching all exceptions (except for 'main()' functions to catch unknown errors) means that the try/catch will process all the exceptions in the same way: 'RuntimeException' will be processed in the same way as application specific exceptions such as 'BankingException' or 'CredentialException'. This will prevent the application from carrying out the specific recovery process that is needed and as a consequence will threaten both application robustness and security.
In addition, an exception carries some additional information on the error conditions. For example, an exception derived from 'std::exception' contains an error message that is returned by the 'what()' function. In a 'catch(...)', all type information about the exception is lost, as well as all additional data provided with the exception.
There are only two actions that can be taken after a 'catch(...)':
- Unconditionally accept the exception, pretending it has never been thrown. This is very bad practice and will most probably produce errors that are very hard to understand and with lots of consequences (for instance, silencing an I/O error may lead to user data loss).
- Break the normal execution of the program, saying that an unknown error has happened (stop the program, automatically restart the program, put the hardware in safe-mode...). This is usually only useful close to the top level of the program, for instance in the 'main()' function.
One usage pattern for which 'catch(...)' might seem useful is for doing resource cleanup when an exception is thrown, and then re-throw the exception, trying to emulate the use of 'finally' in C++. However, the usage of "RAII":http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization is a preferred solution to resource cleanup, it is safer to use and requires less work from the developer.
Remediation
Except for 'main()' or other top-level functions, always use the appropriate type of catch and specific recovery code.
Violation Code Sample
try
{ /*...*/ }
catch (...) // <= VIOLATION
{ /*...*/ }
Fixed Code Sample
try
{ /*...*/ }
catch (SpecificException &e)
{ /*...*/ }
Related Technologies
C++
Technical Criterion
Programming Practices - Error and Exception Handling
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.