32

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?

João Pereira
  • 673
  • 1
  • 9
  • 29
qed
  • 22,298
  • 21
  • 125
  • 196
  • Tangential: given "C++ Exception" is function-local and has automatic storage, could what() throw `std::badalloc` if you were out of memory? – RJFalconer Mar 12 '14 at 13:33
  • @rjfalconer why do you think that has automatic storage? The unnamed pointer return value does, but the array? – Yakk - Adam Nevraumont Mar 12 '14 at 13:36
  • Ah yes. I'm ignoring the return type. So same question then but for any arbitrary example where automatic storage is used: would that prohibit the use of such an exception specifier? – RJFalconer Mar 12 '14 at 13:41

3 Answers3

34

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.

Sebastian Redl
  • 69,373
  • 8
  • 123
  • 157
13

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.

anderas
  • 5,744
  • 30
  • 49
8

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/

Engineer2021
  • 3,288
  • 6
  • 29
  • 51