Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to inherit from std::exception

Tags:

c++

exception

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."); 
like image 280
smallB Avatar asked Nov 16 '11 13:11

smallB


People also ask

Should all exceptions inherit from std :: exception?

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.

What must a class inherit from in order to be used to throw an exception?

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).

What is std :: exception in C++?

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.


1 Answers

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.

like image 171
obmarg Avatar answered Sep 20 '22 14:09

obmarg