I’m trying to wrap my head around exceptions and more I guess what they can do and even more important what they should and shouldn’t do.
So, I’ll go off with an example of how I am thinking at a pretty specific problem and hope that people will either bless or bash the ideas I’m having.
I’m reading settings off of a xml file, so I might have the settings but there is also the case where the specific setting might not be in there and that’d yield some troubles and a lot of “point-error-handling” or what to call it, of the type:
(observe: this is not “real code” but just some pseudo stuff hopefully making my point).
if (xml.attribute("some_attrib")) {
settingForSomeAttrib = xml.attribute("some_attrib")->value();
} else {
settingForSomeAttrib = "some default value";
}
So this will leave me with a check and an assignment more or less for every- and anything I’d like to do, which isn’t desirable.
Then I were thinking, perhaps I could run through it all, fetch anything which went wrong and hand it the default value, a bit of a just try to get it right and anything which didn’t work out we’ll handle afterwards..
Leading me to a try/catch type of thinking.
I am then thinking that perhaps I can do a try block:
try {
setting1 = xml.attribute("attr1")->value(); // throws some kind of "attr1" exception?
setting2 = xml.attribute("attr2")->value(); // -||- "attr2" exception?
} catch (???) {
//go through the things which went wrong and set them settings straight!
}
Hope that makes some kind of sense, or at least that it’s possible to follow my train of thought. I feel that it’s not really how exceptions are meant to be used.
I am thinking that my question is kind of two folded by this:
1) Is exceptions usable like this or is this just a bad idea?
2) how do people usually go about this in C++ to get code that aren’t all bloated in checking for validity?
Thanks.
I would certainly not use exceptions to handle settings that are merely optional.
Instead, I would do something along the following lines: