15.1 Throwing an exception

15.1.1 Only use instances of std::exception for exceptions

Exceptions pass information up the call stack to a point where error handling can be performed. If an object of class type is thrown, the class type itself serves to document the cause of an exception. Only types that inherit from std::exception, should be thrown.

#include <cstdint>
#include <stdexcept>
#include <iostream>
               
int foo ();
               
void bar ()
{
try
{
if (0 == foo ())
{
throw -1;     // @@- Non-Compliant -@@
}
}
catch (int32_t e) // @@- Non-Compliant -@@
{
}
                 
try
{
if (0 == foo ())
{
throw std::runtime_error ("unexpected condition"); // @@+ Compliant +@@
}
}
catch (std::exception const & e)                       // @@+ Compliant +@@
{
std::cerr << e.what ();
}
}

If an instance of an object inheriting from std::exception is created, then such an object must appear in a throw expression.

#include <exception>
               
class MyException : public std::exception
{
// ...
};
   
void f1 ()
{
MyException myExcp;   // @@- Non-Compliant -@@
}
   
void f2 ()
{
MyException myExcp;   // @@+ Compliant +@@
throw myExcp;
}

References

  • HIC++ v3.3 – 9.2

Click here for references