Can what() return NULL for exceptions?

c++, exception, inheritance

Solution

The contents of the string is implementation defined, so I guess the answer is yes.

Edit: Belay that. The standard says:

virtual const char* what() const throw();
5 Returns: An implementation-defined NTBS.

So it must return a string, not just a pointer. And a string cannot be `NULL`. As others have pointed out it is easy to derive exceptions whose `what()` does return `NULL`, but I'm not sure how such things fit into standards conformance. Certainly, if you are implementing what() in your own exception class, I would consider it very bad practice to allow it to return NULL.

More:

For a further question addressing whether `what()` can return NULL, and similar exciting issues, please see Extending the C++ Standard Library by inheritance?

Problem

Can a caught `std::exception`'s `what()` return `NULL`? Is the checking for `e.what()` below necessary? ``` // ... } catch (const std::exception& e) { std::string error; if(e.what()) error = e.what(); } ```

Original source

Related problems