Search code examples
c++exceptiongoto

Is using 'goto' in exception handlers bad style?


Since I started programming I was taught to never use 'goto' if it can be avoided. I, however, came across a case where I think goto is the easiest way to keep this code clean.

My code looks like the following example:

// code within a for-loop
// ...
// ...
try{
      if(!ifstream.open())
          throw special_exception;

      A_EXCEPTION_HANDLED:
//...
//...
}
catch(special_exception ex)
{
  // trying to fix the error here
  if(error_is_fixed)
     goto A_EXCEPTION_HANDLED;

  // else clean up and show error message
};

This example is inside a nested loop and I need to be sure that the code following the throw is executed properly so I would have to write a lot of overhead to start the iteration, in which the exception was thrown, again. Would this case be considered as fair use of goto or is it as bad style as jumping out of loops etc. ?


Solution

  • I think based on your description the code can be rewritten like this:

    for ( /* usual stuff */ )
        try{
              if(!ifstream.open())
                  throw special_exception;
        } catch (const special_exception&) {
            if (/* "can't handle the truth!" */) {
                // clean up & show error message
                break;
            }
        }
        // OK, continue
    }