C++ function declaration followed by throw of of must see

  • 2020-05-10 18:34:52
  • OfStack

Problem description:

Why is C++ sometimes followed by the throw() keyword in function declarations?


Explanation:

The keyword throw(something) is added after the C++ function to limit the exception security of this function. This is an exception specification that only occurs when a function is declared, indicating that the function may throw any type of exception.


throw void fun () ();           // means that the fun function is not allowed to throw any exceptions, which means that the fun function is exception safe.

void fun () throw (...). ;       // means that the fun function can throw any kind of exception.

void fun () throw (exceptionType);       // means that the fun function can only throw exceptions of type exceptionType.


Examples:

void GetTag () throw (int);                                         // means that only int type exceptions are thrown
void GetTag() throw(int, char);               // throws an in, char type exception
throw void GetTag () ();                                       // means that no type exception will be thrown
void GetTag () throw (...). ;                             // Means that any type of exception is thrown

void GetTag () throw (int); Means that only int type exception is thrown, which does not mean that 1 will definitely throw an exception, but 1 will only throw an exception of int type. If a non-int type exception is thrown, unexsetpion() function is called to exit the program.

throw void GetTag () ();   if you add an throw() attribute to your function that never throws an exception, the compiler will be very smart about the intent of the code and how to optimize it.


Related articles: