What is the use of throw() after a function declaration?

Viewed 112

Throw is defined as a C++ expression in https://en.cppreference.com/w/cpp/language/throw. Syntactically, it is followed by an exception class name. For example:

int a = 1, b = 0; 
if (b==0){
    string m ="Divided by zero";
    throw MyException(m);       //MyException is a class that inherit std::exception class
}

However, I have seen other syntaxes with throw that I don't quite understand:

void MyFunction(int i) throw();     // how can we have an expression following a function definition? 

or within a custom exception class, we also have:

class MyException : public std::exception
{
public:
  MyException( const std::string m)
    : m_( m )
  {}

  virtual ~MyException() throw(){};               // what is throw() in this case? 
  const char* what() const throw() {                       // what are the parentheses called? 
      cout<<"MyException in ";
      return m_.c_str(); 
  }

private:
  std::string m_;
};

Therefore, my questions are:

  1. Is there a common syntax rule that allows an expression followed by a function definition?
  2. Why do we have parenthesis following an expression throw? What are they called in C++?
1 Answers

throw() is not a throw expression. It is a completely independent syntax construct that just happens to look the same (C++ likes to reuse keywords for multiple purposes instead of reserving more identifiers). The position where throw() is used in your examples is not a position where the grammar of the language expects an expression, therefore it can't be a throw expression. Additionally () is not a valid expression (as would be required after throw in a throw expression) either.

It is the syntax to declare a non-throwing dynamic exception specification for a function, meaning it declares that the function does not throw any exceptions.

The syntax has been deprecated since C++11 and has finally completely been removed from the language with C++20. Therefore it shouldn't be used anymore.

The exact mechanism of the dynamic exception specification has no replacement, but specifically the non-throwing declaration throw() has been superseded by the noexcept specifier (since C++11). So all uses of throw() on a function declaration in old code should be updated to noexcept instead.

Related