Why is this an issue?
While exceptions are a common feature of modern languages, there are several reasons to potentially avoid them:
- They make the control flow of a program difficult to understand, because they introduce additional exit points.
- The use of exceptions in new code can make that code difficult to integrate with existing, non-exception-safe code.
- They add to the size of each binary produced, thereby increasing both compile time and final executable size.
- They may incur a small performance penalty.
- The time required to handle an exception is not easy to assess, which makes them difficult to use for hard real-time applications.
This rule raises an issue when:
- an exception is
throw
n
- a
try
-catch
block is used
- an exception specification (
throw(xxx)
) is present.
Noncompliant code example
This C++ code example also applies to Objective-C.
double myfunction(char param) throw (int); // Noncompliant
void f {
try // Noncompliant
{
do_something();
throw 1; // Noncompliant
}
catch (...)
{
// handle exception
}
}
Compliant solution
double myfunction(char param) noexcept;
bool f {
if (!do_something()); {
// Handle the situation
return false;
}
// Rest of the code
return true;
}
Exceptions
noexcept
specifications are ignored, because even if you choose not to use exceptions in your code, it’s important to decorate as
noexcept
certain functions (for instance, move constructors that do not throw
). This decoration can be detected by type
traits, and some meta-programming techniques rely on this information.