Search code examples
design-patternspseudocode

Code Patterns: Breaking from a do-once loop


Consider the following design pattern:

do {
    // Some logic here
    if (AnErrorOccurs()) {
        break;
    }
    // Some more logic here
    if (ADifferentErrorOccurs()) {
        break;
    }

    // Code completed successfully
    return someValue;
} while (false);

// Lengthy error-handling code here
return errorCode;

Is using a loop in this way appropriate? I simply want the functionality of the break statement so that I can put my error handling code in one place. A separate method would work too, true, but suppose there's a large number of variables in scope that would be unwieldy or unsafe to pass around as parameters.

Or would the try-finally pattern be a better way of handling this situation? Or throwing a whole bunch of custom exceptions? I'm just interested to see how others handle it in the interest of having the neatest and most maintainable code.


Solution

  • I think you should use try catch statement instead of do while if you want to handle exception, since code should be able to self-document without putting comments here and there. If you want to handle exception in your code, wouldn't try catch statement seems more appropriate? With that said I think it is better to have the custom exceptions in the try catch for handling your specific exceptions.

    The exception would be thrown in the method which need any specific conditions. For example, Convert.toInt32(string s) here. This Convert.toInt32(string s) would throw either FormatException or OverflowException when the condition doesn't meet. There is no try catch in that method. The try catch would be placed in a method which call Convert.toInt32(string s).