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

Igor
  • 26,650
  • 27
  • 89
  • 114
MainID
  • 29,070
  • 19
  • 57
  • 70

3 Answers3

8

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

Alex B
  • 82,554
  • 44
  • 203
  • 280
  • Perhaps, "is not supposed to throw" then. – Alex B Feb 01 '09 at 22:13
  • It might be better to phrase it as: "An exception will not be propagated outside of that function". Your program might "terminate" if an exception is thrown from within that function, but it won't be propagated. – Richard Corden Feb 02 '09 at 10:52
4

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 Comment@onebyone.livejournal.com): 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.

Community
  • 1
  • 1
Martin York
  • 257,169
  • 86
  • 333
  • 562
3

The const qualifies the function what(), saying it does not modify the internal structure of the exception object.

The throw() means it doesn't throw an exception, either - as noted by OneByOne and Checkers.

The two words are largely unrelated, even though they appear right next to each other in the signature.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278