Reputation: 23104
Here is from http://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.htm
#include <iostream>
#include <exception>
using namespace std;
struct MyException : public exception
{
const char * what () const throw ()
{
return "C++ Exception";
}
};
I understand the const
after what
means the function does not modify any
members of the struct, but what does the throw()
at the end mean?
Upvotes: 33
Views: 25249
Reputation: 5844
throw ()
is an exception specifier that declares that what()
will never throw an exception. This is deprecated in C++11, however (see http://en.wikipedia.org/wiki/C++11). To specify that a function does not throw any exception, the noexcept
keyword exists in C++11.
Upvotes: 14
Reputation:
You can specify the type being thrown so that if it throws anything but that type (e.g.
int
), then the function callsstd::unexpected
instead of looking for a handler or callingstd::terminate
.In this case, it won't throw any exceptions, which is important for
what()
.If this throw specifier is left empty with no type, this means that
std::unexpected
is called for any exception. Functions with no throw specifier (regular functions) never callstd::unexpected
, but follow the normal path of looking for their exception handler.This is called dynamic exception specifications and it was common in older code. It is considered deprecated.
See here: http://www.cplusplus.com/doc/tutorial/exceptions/
Upvotes: 8
Reputation: 71899
It means it won't throw any exceptions. This is an important guarantee for a function like what
, which is usually called in exception handling: you don't want another exception to be thrown while you're trying to handle one.
In C++11, you generally should use noexcept
instead. The old throw specification is deprecated.
Upvotes: 36