...
This compliant solution assumes that the type of the exception object can inherit from std::runtime_error
, or that type can be used directly. Unlike std::string
, a std::runtime_error
object is already required to correctly handle an arbitrary-length error message that is exception safe and guarantees the copy constructor will not throw [ISO/IEC 14882-2014]:
Code Block | ||||
---|---|---|---|---|
| ||||
#include <stdexcept> #include <type_traits> struct S : std::runtime_error { S(const char *msg) : std::runtime_error(msg) {} }; static_assert(std::is_nothrow_copy_constructible<S>::value, "S must be nothrow copy constructible"); void g() { // If some condition doesn't hold... throw S("Condition did not hold"); } void f() { try { g(); } catch (S &s) { // Handle error } } |
...
[Hinnant 2015] | |
[ISO/IEC 14882-2014] | Subclause 15.1, "Throwing an Exception" |
...