G
Goran
It seemed to me you are talking about inspecting the thrown object
dynamically for real errors is the correct way.
Hmmm... No, not necessarily. Exception object IMO should carry good
info about the original error, and should rarely be "inspected".
Exceptions work well in situations where it's useless to try to
continue running the started operation (that does not necessarily mean
"useless to run the whole program"). They should signal what could not
be done, and somewhere high up the stack, they should be used to
inform the user/operator what failed. Occasions where it's needed to
"inspect" them in order to take further action (corrective action?
perhaps) should be rare. If your code has that need, I'd say, derive a
specific exception type, so that you can catch that type specifically.
Then you know what's inside and why was it thrown.
I switch to normal codes because this can serve as a hint to the
answer of the other thread. (But I am not familiar with standard
library, I use mine.)
std::vector<T> v1,v2;
.....
try { v1.insert(itr,v2); }
catch(const std::invalid_argument& e) {
// Run-time check e for the real meaning, never by type.}
catch(const std::length_error& e) {
// Run-time check e for the real meaning, never by type.
};
Again, the code you put here is in my opinion completely wrong. Both
invalid_argument and length error signal programming errors (they both
derive from logic_error). It is therefore useless to catch them the
way you've shown. Frankly, it's not the first time I, and others, tell
you "that's not what you should do", and you continue to say "it's
broken if I do it".
What you should instead do, is let all your logic_error exceptions
propagate up to the highest possible stack level (e.g. main), catch
and terminate there (you could inform the operator/user that you
encountered a bug in the program). And perhaps not even that, perhaps
you should just let unhandled exception terminate the program (but
then, it's less clear what happened).
Why like this? Because logic_error means there is a bug in program
(and if it does not mean that, then the bug is that logic_error is
thrown when it should not have been thrown).
Goran.