Own Exception class derived from runtime_error

A

amphetaman

If I derive my own Exception class from std::runtime_error, do I have
to write the destructor even if its body is empty?

#include <stdexcept>

class Exception : public std::runtime_error
{
public:
explicit Exception(const std::string &description) :
std::runtime_error(description) { }
virtual ~Exception() throw() { } // Do I need to write this?
};
 
A

acehreli

And if I derive other classes from that Exception class?

Every class takes care of itself. You don't need to worry about the
base classes because the destructors are called recursively by code
generated by the compiler. The order is the reverse of the
construction order.

Ali
 
J

James Kanze


Maybe.

The destructor of std::runtime_error has an empty exception
specification, which means that all destructors of classes
derived from it must also have empty exception specifications.
§15.5/13 describes how the exception specification of an
implicitly generated function is generated; the important point
here is that the exception specification will only be empty if
all of the functions called by the generated function also have
empty exception specifications.

If the compiler generated destructor only calls the
std::runtime_error destructor, there is no problem. If the
class has additional members of class type, however, there is
likely to be a problem, because a lot of classes (e.g.
std::string, boost::shared_ptr...) even if they never throw. If
your derived class uses any of these, you'll need to declare and
defined an empty destructor, with an empty exception
specification (and exceptions are one case where
boost::shared_ptr makes a lot of sense, since it is guaranteed
to be able to copy without throwing---unlike classes like
std::string, which may do a deep copy).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top