I'm convinced at this point that I should be creating subclasses of std::exception
for all my exception throwing needs. Now I'm looking at how to override the what
method.
The situation that I'm facing, it would be really handy if the string what
returns be dynamic. Some pieces of code parse an XML file for example, and adding a position or line number to the error message is useful to me.
I am trying to follow the Boost Exception handling guidelines.
What I'd like to know:
what
returns aconst char *
, which implies any catcher is likely not going to free the string. So I need some other place to store the result, but where would that be? (I need thread-safety.)what
also includesthrow()
in its signature. While I can prevent mywhat
from throwing anything, it seems to me that this method really isn't intended for anything too dynamic. Ifwhat
is not the right place, then where should I be doing this instead?
From the answers I've gotten so far, it looks like the only way to accomplish this is by storing the string in the exception. The Boost guidelines recommend against this, which is confusing to me, because std::runtime_error
does just that.
Even if I were to use a C-string, I'd have to use a statically sized buffer, or do memory management which can fail too. (I'm wondering if this is actually the only thing that can go wrong in std::string
's copy-constructor. That would mean I won't gain anything using dynamically allocated C-strings.)
Is there any other option left?