Explanation to the what() call

2020-05-21 07:55发布

问题:

using namespace std;

struct MyException : public exception
{
  const char * what () const throw () // <--- This
  {
    return "C++ Exception";
  }
};

Please consider the marked line. Can somebody explain me the syntax used in that statement

I think i should have narrowed down my query to "const throw()" part only...

Thanks all for the replies

回答1:

It's a member function definition.

  • const char * is the return type, a pointer to a constant character, by convention the first character of a zero-terminated string array.
  • what is the function name
  • () is an empty parameter list, indicating that the function takes no arguments
  • const qualifies the function, so it can be called on a const object, and can't directly modify the object's members
  • throw () is an exception specification which prevents it from throwing any exceptions.

This overrides the virtual function declared in the exception base class, allowing you to get a text message describing the specific exception that was thrown:

try {
    // Throw a specific type
    throw MyException();
} catch (std::exception const & ex) {
    // Catch a generic type and extract the message
    std::cerr << ex.what() << '\n';  // prints "C++ Exception"
}


回答2:

what is a function that returns a const char *. It is also a function that never throws an exception.



回答3:

The line is a member function declaration for the class MyException. It follows the exact same syntax as any other function declaration.

const char * - is the return type of the function.

what - is the name of the function.

() - the (empty) parameter list. The method takes no parameters.

const - declares this to be a const function (in general, this means it should not change the state of the object).

throw () - declares that the function throws no exceptions.



回答4:

using namespace std;

struct MyException : public exception
{
  const char * what () const throw () // <--- This
  {
    return "C++ Exception";
  }
};

It isn't clear from your question which bit in particular you are unsure of, but I would guess it is the throw(), as this is not commonly used.

This is used to document the types of exceptions the method can throw, which enables the compiler to check that:

  1. When you use the method ,You are catching everything thrown
  2. Are not throwing something that you should not be

The rest of the line is fairly standard:

const char * what () const throw ()

what() : A function named what.

what() const: what() is a const function, so it can be used on const objects of type MyException

const char* what() const: what is a const function, which returns a pointer to const char



标签: c++ syntax