Re: Exception handling
On 3/3/07 9:50 AM, in article
1172932656.995873.279070@j27g2000cwj.googlegroups.com, "Rune Allnor"
<allnor@tele.ntnu.no> wrote:
I have made a class for some data manipulation that tests for
data integrity before emarking on the processing. The class
contains a number of methods which test for certain error
conditions and throw exceptions if the errors are present
in the data.
Some of the errors, "annoying" errors, can be fixed automatically
when detected, and the routine can have another go at validating
the data before processing. Other errors, "serious" errors, have
to be piped on to the user to resolve.
The naive idea is easily expressed as:
try {
x->validate();
} catch (annoying) {
// repair whatever condition
try{ //<----- Recursive try-catch loop
x->validate(); //<-----
} //<-----
catch() {...} //<-----
}
catch(serious)
{
throw;
}
Since repairing a minor problem causes the program to return to the exact
same state as it had before the repair (that is, ready to validate the
input), it should also be the case that the program would be at the same
point in its execution sequence both before and after performing the repair.
In other words, the cycle of: validate-repair-validate is iterative - not
recursive - so its implementation in code should be as well:
struct MinorIssue {};
struct MajorProblem {};
void run( X* x)
{
assert( x != NULL);
while (true)
{
try
{
x->validate();
x->process();
break;
}
catch ( MinorIssue& annoyMe)
{
x->repair();
}
}
}
Even though x->process() does not throw MinorIssues itself, there is no harm
in including the call to process() within the same try clause as the call to
validate(). Note also that any MajorProblems thrown while validating the
input are not caught at this level - but are destined for a catch clause in
some, enclosing scope.
Now, the correctness of this code naturally depends on x->repair() actually
making the input acceptable to x->validate() after some reasonable number of
attempts. If no such certainty exists, then the loop should increment a
counter upon each iteration of the while loop. If the program iterates
through the loop a predetermined number of times without exiting, then this
routine would give up and throw a MajorProblem exception on its own that
some higher-up routine would know how to handle.
Greg
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]