Question related to getting standard exception classes

/* 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 ()? Usually, if there is throw (), this means that the function before throw () can throw an exception. However, why is there a throw?

+4
source share
3 answers

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

+8
source

const is a separate throw () problem.
This means that it is a const method. Thus, calling this method will not change the state of the object.

throw () means that the method will not throw any exceptions.

In the USER of this method, the method will only return in the normal way, and you do not need to worry about the exceptions that cause the call.

The IMPLEMENTER method is more worried.
Unlike Java, this is not a compilation time limit, but a run-time limit. If the executor writes this function so that it accidentally throws an exception to the method, then the execution time will stop the application dead (without expanding the stack without destructors, etc.).

But the agreement is that the developer will take extra precautions to catch all the internal exceptions.

PS
You can get from std :: runtime_error

(From Comment@onebyone.livejournal.com ): Not really.
The no throw specifier is actively used. This exception safety measure indicates that the method provides a no-throw guarantee.

On the other hand, other exception specifiers are not used because they are too dangerous. If you make a mistake, this will lead to the termination of the application via (std :: unexpected). The default action is to terminate the application without unwinding the stack and without cleaning it using object destructors. In MHOP, this is hardly desirable.

+4
source

const qualifies the what() function by saying that it does not change the internal structure of the exception object.

throw() means it does not throw() an exception - as indicated by OneByOne and Checkers.

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

+3
source

All Articles