[Tutor] try except continue

Alan G alan.gauld at freenet.co.uk
Thu Jul 28 23:25:15 CEST 2005


> program, when it runs through its steps and encounters an error, to 
> log
> the error and pick up where it left off and keep going.  According 
> to this
> link, 'continue' is allowed within an except or finally:

Thats true but only if the try block is inside a loop.
Consider:

error = True

def f():
   if error: raise ValueError
   else: print 'In f()'

def g():
   print 'In g()'

while True:
  try:
    f()
    g()
  except ValueError:
       error = False
       continue

continue will cause the *next* iteration of the loop to start. Thus
the first time round the error is raised in f() and the code jumps
to the except clause and from there back to the top of the loop,
effectively missing g() out, then next time through no error is
raised so both f() and g() are called.

If you really want to ignore the error and move to the next line you
have to do a try:except on every line (or function call)

try: f()
except: pass
try: g()
except: pass

Or put the functions in a list if their parameter lists are null
or identical:

funcs = [f,g]
for func in funcs:
   try: func()
   except: continue

But all of that's bad practice since who knows what nasties you
might be allowing through. Its usually possible to structure
code to avoid such horrors!

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Tutor mailing list