throw () after function declaration in c++ excepti

2020-05-25 07:54发布

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?

3条回答
霸刀☆藐视天下
2楼-- · 2020-05-25 08:06

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/

查看更多
时光不老,我们不散
3楼-- · 2020-05-25 08:11

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.

查看更多
Fickle 薄情
4楼-- · 2020-05-25 08:16

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.

查看更多
登录 后发表回答