/* user-defined exception class derived from a standard class for exceptions*/
class MyProblem : public std::exception {
public:
...
MyProblem(...) { //special constructor
}
virtual const char* what() const throw() {
//what() function
...
}
};
...
void f() {
...
//create an exception object and throw it
throw MyProblem(...);
...
}
My question is why there is a "const throw()" after what()? Normally,if there is a throw() , it implies that the function before throw() can throw exception.However ,why there is a throw here?
Empty braces in "throw()"
means the function does not throw.
The const is a separate issue to throw().
This indicates that this is a const method. Thus a call to this method will not change the state of the object.
The throw() means the method will not throw any exceptions.
To the USER of this method, the method will only return through normal means and you do not need to worry about the call generating exceptions.
To the IMPLEMENTER of the method there is more to worry about.
Unlike Java this is not a compile time constraint but a runtime constraint. If the implementer writes the function so that it accidentally throws an exception out of the method then the runtime will stop the application dead (no unwinding of the stack no destructors etc).
But the convention is that the implementer will take the extra precautions to catch all internal exceptions.
PS
You may want to derive from std::runtime_error
(From [email protected]): Not quite.
The no throw specifier is actively used. It is an indication of exception safety demonstrates that the method provides the no throw guarantee
On the other hand the other exception specifiers are not used because they are too dangerous. If you get them wrong it causes an application termination via (std::unexpected). The default action is application termination without unwinding the stack and without cleaning up using object destructors. In MHOP this is hardly ever desirable.
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