I was writing code with exception handling the other day, and I had a few questions about exceptions, their guarantees and throwables.
Basically, say you have:
class X {
string m_str;
X() : m_str("foo")//what if this throws?
{
ifstream b("a.in")//what if this throws?
}
And after running through all the articles I could find, I still have no idea what is the clean way to handle this.
Say I have a code like:
{
...
X myInstanceOfClassX;
...
}
Should I wrap the code in catch(exception &)
? And if I do that, does string
and ifstream
guarantee a strong guarantee, that no resources are leaked and nothing has been left half opened?
Also, if my class throws myexception
, that is derived from exception, catch(exception &)
seems to let it through. So that leaves me with catch(...)
which IIRC catches access violation?.? Is there another way?
Then there was a piece of information somewhere that any exception thrown in subconstructors of object constructor shouldn't be caught, and constructor should throw in case any of the member objects throw.
And what if the code above would have been called not from constructor, but from regular a function void foo()
, which exceptions should I catch? outofmemory_something, filenotfound_something? Where can I find the definitions of what STL objects can throw? Are they implementation specific?
Where is the authoritative source where I could clear all my doubts and questions on this topic?
So far, it seems that handling exceptions is like dancing in a big pile of gooo. Error codes seem A LOT simpler and safer...