Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using multiple exceptions in python

Is there a way to use multiple exceptions in python? Like code below:

try:
   #mycode
except AttributeError TypeError ValueError:
   #my exception

What I mean is how to use AttributeError TypeError ValueError with each other?

like image 854
hamidfzm Avatar asked Jan 18 '26 19:01

hamidfzm


1 Answers

Use a tuple:

try:
   # mycode
except (AttributeError, TypeError, ValueError):
   # catches any of the three exception types above

Quoting the reference try statement documentation:

When an exception occurs in the try suite, a search for an exception handler is started. This search inspects the except clauses in turn until one is found that matches the exception.
[...]
For an except clause with an expression, that expression is evaluated, and the clause matches the exception if the resulting object is “compatible” with the exception. An object is compatible with an exception if it is the class or a base class of the exception object or a tuple containing an item compatible with the exception.

Emphasis mine.

like image 181
Martijn Pieters Avatar answered Jan 20 '26 10:01

Martijn Pieters