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.
How do I catch both exceptions at once?
try:
print myobject.a
except NameError:
pass
except AttributeError:
pass
In C#, You can use more than one catch block with the try block. Generally, multiple catch block is used to handle different types of exceptions means each catch block is used to handle different type of exception.
Java allows you to catch multiple type exceptions in a single catch block. It was introduced in Java 7 and helps to optimize code. You can use vertical bar (|) to separate multiple exceptions in catch block.
When catching multiple exceptions in a single catch block, the rule is generalized to specialized. This means that if there is a hierarchy of exceptions in the catch block, we can catch the base exception only instead of catching multiple specialized exceptions.
Yes you can have multiple catch blocks with try statement. You start with catching specific exceptions and then in the last block you may catch base Exception . Only one of the catch block will handle your exception.
Just use parentheses:
try:
print myobject.a
except (NameError, AttributeError):
pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With