"Goto" statement in Python

Grant Edwards grant.b.edwards at gmail.com
Thu Apr 13 14:24:53 EDT 2017


On 2017-04-13, Rob Gaddi <rgaddi at highlandtechnology.invalid> wrote:

> No, C doesn't support exception handling.  As a result, handling error 
> conditions in C is a huge pain for which (forward-only) goto is often, 
> while not the only remedy, the least painful one.

Indeed. That is almost the only place I use 'goto' in C, and the
almost the only place I see others use it.  Very occasionally, you see
a the error handling goto refactored into a backwards "goto retry":

this code

foo()
  {
  while (1)
    {
      <some code>
      if (<some-error-condition>)
           goto error:
      <more code>
      return;

    error:
      <recover-from-error-condition>
    }
  }

becomes

  foo()
  {
    retry:
      <some code>
      if (<some-error-condition>)
        {
           <recover-from-error-condition>
           goto retry:
        }
      <more code>
  }

I happen to find the latter easier to read.

Fortunately, Python doesn't need goto to deal with things like that.

> Or if you've really developed a need for self-harm, setjmp/longjmp.

I've tried to use setjmp/longjmp for error handling a few times.  It
never went well...

-- 
Grant Edwards               grant.b.edwards        Yow! Catsup and Mustard all
                                  at               over the place!  It's the
                              gmail.com            Human Hamburger!



More information about the Python-list mailing list