I have the following pattern:
private void MyFunction()
{
doStuff();
if (problem())
{
cleanup();
return;
}
doMoreStuff();
if (otherProblem())
{
cleanup();
return;
}
doYetMoreStuff();
}
The error cleanup code is duplicated. The obvious way to eliminate this is:
private void MyFunction()
{
try {
doStuff();
if (problem()) throw new MyException();
doMoreStuff();
if (otherProblem()) throw new MyException();
doYetMoreStuff();
}
catch (MyException)
{
cleanup();
return;
}
}
However, the error cases are not really exceptional - this is an ASP.Net page, and bad or no data in the query string will trigger the error cases. Exceptions seem to be the most obvious way to deduplicate the error handling and separate it from the main code, but as I understand it the accepted best practice is not to use exceptions for control flow like this.
What is the customary way of doing this?