Only instances of types derived from std::exception should be thrown
Only instances of types derived from std::exception should be thrown.
Raising generic objects as exceptions can make your code difficult to read and reuse.
Consider this code where exceptions are raised in two different try-catch
blocks.
try{
//..
throw 1; // 1 means logic error;
}
catch(...){
//...
}
//...
try{
//...
throw std::logic_error{"Logic Error"};
}
catch(std::exception& e){
//..
}In the second code block, the meaning and cause of the exception is clearly communicated
by raising a specific and unique type of object as an exception. Such
throw statements also match standard conventions. Clearly communicating
the developer intent, adhering to the standard conventions, and raising unique type of
exceptions make the code easy to read, understand, and reuse.
The class std::exception provides a consistent interface to raise
unique exceptions corresponding to specific errors. It is standard convention to use this
interface for raising exceptions. To make your code readable and reusable, raise objects of
specific types that are derived from std::exception as the exception.
Generic objects of type std::exception cannot be unique. Such exceptions
violate this rule.
Polyspace® flags a throw statement if the type of the raised
object is not a class that is publicly derived from
std::exception.
If the raised object is part of a multiple inheritance hierarchy, then Polyspace flags the object if none of the base classes derive publicly from
std::exception or if the base classes do not include
std::exception.
If you use a throw; statement without an argument in a catch
block, Polyspace does not flag the throw; statement.
If you expect a rule violation but do not see it, refer to Coding Standard Violations Not Displayed.
| Group: Exception handling |
| Category: Advisory, Automated |