7

I want to print an attribute from an object that may not exist yet or may be initialized to None.

I'm wrapping it in a try/except. However, the two exceptions I want to catch are NameError when trying to access a variable that doesn't exist, or an AttributeError when trying to access an attribute of an object that doesn't exist.

Question

How do I catch both exceptions at once?

What I've done

try:
    print myobject.a
except NameError:
    pass
except AttributeError:
    pass
piRSquared
  • 285,575
  • 57
  • 475
  • 624

1 Answers1

7

Just use parentheses:

try:
    print myobject.a
except (NameError, AttributeError):
    pass
Christian Dean
  • 22,138
  • 7
  • 54
  • 87