Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I catch multiple error types [duplicate]

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
like image 309
piRSquared Avatar asked Sep 05 '16 23:09

piRSquared


People also ask

Is there a way to catch multiple exceptions at once and without code duplication?

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.

How do you catch multiple exceptions in one catch?

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.

Can you catch multiple exceptions?

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.

Can you have 2 Catch statements?

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.


1 Answers

Just use parentheses:

try:
    print myobject.a
except (NameError, AttributeError):
    pass
like image 78
Christian Dean Avatar answered Sep 20 '22 05:09

Christian Dean