3 ms·
Yeah, sometimes, using exception as control flow is the only simple and clear way. I do use it occasionally. ex. Lets assume that a problem can be attacked as
by guilloche 14y ago
Yeah, sometimes, using exception as control flow is the only simple and clear way. I do use it occasionally.
ex. Lets assume that a problem can be attacked as algorithm1 (A1), and algorithm2 (A2). A1 is fast but cannot handle some corner cases while A2 is slow and can handle all cases. we also assume that there is no easy way to tell whether A1 is good or not without invoking A1.
So the function can be implemented as:
void A()
{
try {
A1();
}
catch (e) {
A2();
}
}
void A1()
{
.....
if(corner case) raise();
.....
}
Is there a simple way to avoid using eceptions here?
- MereInterest 14y agoYup. Have some sort of error code that is passed back by A1() or A2(). bool A1(); bool A2(); void A(){ bool result = A1(); if (!result){ A2(); } } Instead of your "if(corner case) raise();", you would then have a "if(corner case) return false;". However, it becomes more difficult if you want a return value. Suppose that your A() function was as follows. double A(){ double result; try{ result = A1(); catch (e) { result = A2(); } return result; } Then, you are already using the return value to indicate something other than success or failure of the operation. You could have A1 and A2 return some special value that wouldn't return normally. For example, if it is some distance, negative values could represent invalid responses. double dist(){ double output = dist1(); if (output==-1) output = dist2(); return output; } However, sometimes any value could be a valid value. Then you need to pass things by pointer or reference in order to have two outputs, one for the value and one for the success/failure. bool A1(double* output); bool A2(double* output); double A(){ double output; bool success = A1(&output); if (!success) A2(&output); return output; } It is in this last case when exceptions start being much cleaner, since they provide a clean way to indicate that the operation has failed.