I've just created exception hierarchy and wanted to pass char*
to constructor of one of my derived classes with a message telling what's wrong, but apparently std::exception
doesn't have constructor which would allow me to do so. Yet there is a class member called what()
which would suggest that some information can be passed.
How can I (can I?) pass text to derived class of a std::exception
in order to pass info with my exception class, so I can say somewhere in the code:
throw My_Exception("Something bad happened.");
All exceptions like bad_alloc, bad_cast, runtime_error, etc generated by the standard library inherit from std::exception. Therefore, all standard exceptions can be caught by reference. Program 1: Below is the illustration of the std::bad_alloc error: using class bad_alloc.
For an objects to be throwable (e.g., throw new ...), it must be constructed from some class in the Throwable hierarchy (either Throwable or one of its subclasses).
Defined in header <exception> class exception; Provides consistent interface to handle errors through the throw expression. All exceptions generated by the standard library inherit from std::exception. logic_error.
If you want to make use of the string constructor, you should inherit from std::runtime_error or std::logic_error which implements a string constructor and implements the std::exception::what method.
Then it's just a case of calling the runtime_error/logic_error constructor from your new inherited class, or if you're using c++11 you can use constructor inheritance.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With