[Tutor] try except block for multiple statements

John Fouhy john at fouhy.net
Tue Dec 2 02:54:26 CET 2008

On 02/12/2008, Bryan Fodness <bryan.fodness at gmail.com> wrote:
> I would like to use a try except to see if a value exists.  But, when I use
> the following, if a does not exist it exits.  I understand why this does
> this, but is there a way to get b,c, and d if a does not exist without using
> a try except for every statement?
> try:
>     fo.write("a = %s\n" %plan.a)
>     fo.write("b = %s\n" %plan.b)
>     fo.write("c = %s\n" %plan.c)
>     fo.write("d = %s\n" %plan.d)
> except AttributeError:
>     pass

AFAIK, no -- but you could always use a loop.

attrs = ['a', 'b', 'c', 'd']
for attr in attrs:
    fo.write('A = %s\n' % getattr(plan, attr))
  except AttributeError:


More information about the Tutor mailing list