throw () after function declaration in c++ excepti

2020-05-25 08:10发布

问题:

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?

回答1:

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.



回答2:

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.



回答3:

You can specify the type being thrown so that if it throws anything but that type (e.g. int), then the function calls std::unexpected instead of looking for a handler or calling std::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 call std::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/