Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A question related to deriving standard exception classes

Tags:

c++

exception

/* 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?

like image 576
MainID Avatar asked Dec 08 '22 08:12

MainID


2 Answers

Empty braces in "throw()" means the function does not throw.

like image 78
Alex B Avatar answered Dec 15 '22 00:12

Alex B


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.

like image 39
Martin York Avatar answered Dec 14 '22 23:12

Martin York