I am coming from a Ruby and Java background and have recently begun exploring C++.
While my initial attempts at creating custom exceptions by simply subclassing exception class failed with obscure, I found the following example posted on a site:
class Exception : public exception
{
public:
Exception(string m="exception!") : msg(m) {}
~Exception() throw() {}
const char* what() const throw() { return msg.c_str(); }
private:
string msg;
};
My understanding of semantics of C++ is not very mature at the moment, and I would like to have a better understanding of what is going on here.
In the statement const char* what() const throw()
what does the part const throw()
do, and what kind of programming construct is it?
Also, what is the purpose and intent of throw()
in the destructor specification ~Exception()
and why do I need to have a destructor specification although I don't need it do something in particular? Shouldn't the destructor
inherited from exception be sufficient?
const
after a method declares that the method does not mutate the object. (There are exceptions, and generally it's used to mean "does not mutate the object in an externally-visible way.)
The throw()
after the method declaration is an exception specification; it's similar to the throws E1, E2
exception specifications that you see in Java. However, in C++, exception specifications are not checked at compilation-time and are generally considered to be mostly useless (they are now deprecated). throw()
is the only somewhat useful form, meaning that the function declares that it must not throw an exception (and if it does, it's a logical error, and the program will invoke an unexpected exception handler, by default terminating the program).
The destructor is explicitly declared because if left unspecified, the compiler will generate a destructor that invokes the base class destructor, and the compiler-generated destructor will not use a throw()
exception specification (despite the fact that throwing exceptions in destructors is never a good idea).