Can a caught std::exception ever have what() being NULL?
Is the checking for e.what() below overhead?
//...
}
catch (const std::exception& e)
{
std::string error;
if(e.what())
error = e.what();
}
Can a caught std::exception ever have what() being NULL?
Is the checking for e.what() below overhead?
//...
}
catch (const std::exception& e)
{
std::string error;
if(e.what())
error = e.what();
}
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 http://stackoverflow.com/questions/1073958/extending-the-c-standard-library-by-inheritance
Of course it can be NULL:
class myexception: public exception
{
virtual const char* what() const throw()
{
return NULL;
}
} myex;
If someone has inherited from std::exception and overridden what to return NULL, then this is possible.
class CMyException : public std::exception
{
...
virtual const char * what () const {return NULL;}
};
Despite Neil's excellent find in the standard, It might still be good to check for NULL. Although the specifications of what child classes of std::exception state they should not return a NULL, nothing in your compiler is going to enforce this and the above code will still be legal according to the language.
This may be an ideal situation to use an assert...
assert(except.what() != NULL);
or
if (except.what() != NULL)
{
... normal processing ...
}
else
{
assert(false);
}
because this is a case where something probably should never ever happen, and you are assuming it shouldn't happen, but would still like to know (in debug mode) when your assumptions are shown to be wrong. Then you can either address your incorrect assumption or address the incorrect code which may be going against your assumption (make sure what() doesn't return NULL).
As many others have pointed out, what()
shouldn't return a null pointer but it might. The runtime overhead of a null test is only incurred in the exceptional case where, presumably, it is less important.
In any case, I'd recommend at least using an assert
.
If code space is also a concern, hopefully the assert
, your testing, code reviews and other QA will be complete enough to track down any offending, non-compliant exceptions before you ship.
Also, be careful with exception handling code that can itself throw (for example, as others have noted, allocating memory with std::string
while processing a std::bad_alloc
exception.)