By inspectorG4dget

2011-06-24 15:55:08 8 Comments

I know that I can do:

    # do something that may fail
    # do this if ANYTHING goes wrong

I can also do this:

    # do something that may fail
except IDontLikeYouException:
    # say please
except YouAreTooShortException:
    # stand on a ladder

But if I want to do the same thing inside two different exceptions, the best I can think of right now is to do this:

    # do something that may fail
except IDontLikeYouException:
    # say please
except YouAreBeingMeanException:
    # say please

Is there any way that I can do something like this (since the action to take in both exceptions is to say please):

    # do something that may fail
except IDontLikeYouException, YouAreBeingMeanException:
    # say please

Now this really won't work, as it matches the syntax for:

    # do something that may fail
except Exception, e:
    # say please

So, my effort to catch the two distinct exceptions doesn't exactly come through.

Is there a way to do this?


@Aaron Hall 2014-06-21 04:20:29

How do I catch multiple exceptions in one line (except block)

Do this:

except (SpecificErrorOne, SpecificErrorTwo) as error:
    handle(error) # might log or have some other default behavior...

The parentheses are required due to older syntax that used the commas to assign the error object to a name. The as keyword is used for the assignment. You can use any name for the error object, I prefer error personally.

Best Practice

To do this in a manner currently and forward compatible with Python, you need to separate the Exceptions with commas and wrap them with parentheses to differentiate from earlier syntax that assigned the exception instance to a variable name by following the Exception type to be caught with a comma.

Here's an example of simple usage:

import sys

except (KeyboardInterrupt, EOFError): # the parens are necessary

I'm specifying only these exceptions to avoid hiding bugs, which if I encounter I expect the full stack trace from.

This is documented here:

You can assign the exception to a variable, (e is common, but you might prefer a more verbose variable if you have long exception handling or your IDE only highlights selections larger than that, as mine does.) The instance has an args attribute. Here is an example:

import sys

except (KeyboardInterrupt, EOFError) as err: 

Note that in Python 3, the err object falls out of scope when the except block is concluded.


You may see code that assigns the error with a comma. This usage, the only form available in Python 2.5 and earlier, is deprecated, and if you wish your code to be forward compatible in Python 3, you should update the syntax to use the new form:

import sys

except (KeyboardInterrupt, EOFError), err: # don't do this in Python 2.6+
    print err
    print err.args

If you see the comma name assignment in your codebase, and you're using Python 2.5 or higher, switch to the new way of doing it so your code remains compatible when you upgrade.

The suppress context manager

The accepted answer is really 4 lines of code, minimum:

except (IDontLikeYouException, YouAreBeingMeanException) as e:

The try, except, pass lines can be handled in a single line with the suppress context manager, available in Python 3.4:

from contextlib import suppress

with suppress(IDontLikeYouException, YouAreBeingMeanException):

So when you want to pass on certain exceptions, use suppress.

@Mache 2019-12-17 09:14:45

Good addition of suppress, a lot more readable than just doing pass on except

@Vorsprung durch Technik 2011-06-24 15:56:34

From Python Documentation:

An except clause may name multiple exceptions as a parenthesized tuple, for example

except (IDontLikeYouException, YouAreBeingMeanException) as e:

Or, for Python 2 only:

except (IDontLikeYouException, YouAreBeingMeanException), e:

Separating the exception from the variable with a comma will still work in Python 2.6 and 2.7, but is now deprecated and does not work in Python 3; now you should be using as.

@BallpointBen 2018-03-22 03:04:33

Is it possible to store desired exceptions in an iterable, and then catch the iterable? I'm trying to turn a list of warnings into errors using warnings.filterwarnings, and I don't want to have to specify the list of warnings twice.

@BallpointBen 2018-03-22 16:02:01

I did try it... with a list, and it resulted in a TypeError. Looks like the errors must be in a tuple for catching to work as expected.

@Vorsprung durch Technik 2018-03-22 16:36:15

Why would you ever have used a list when you see clearly that it is documented that a tuple is needed in this case?

@BallpointBen 2018-03-22 16:48:21

It was unclear whether the "parenthesized tuple" was merely syntactical or that a bona fide tuple was required. "Parenthesized" is misleading because you may create a tuple without parentheses elsewhere and then use it in the except line. It is only necessarily parenthesized if created in the except line.

@Joseph Bani 2019-02-25 07:27:53

Anything parenthesized in python is a tuple

@jammertheprogrammer 2019-04-12 00:09:22

@JosephBani, what about generator expressions?

@Soren Bjornstad 2019-07-12 20:25:03

@JosephBani That's not true at all. In 2 + (x * 2), (x * 2) is certainly not a tuple. Parentheses are a general grouping construct. The defining characteristic of a tuple is that it contains a comma -- see the Python documentation: "Note that it is actually the comma which makes a tuple, not the parentheses."

@fantabolous 2019-10-25 07:24:13

When you're not actually using the e (as in this case) you can just drop the as e or , e and then python 2 and 3 are the same ;)

@whitebeard 2017-09-18 01:36:57

If you frequently use a large number of exceptions, you can pre-define a tuple, so you don't have to re-type them many times.

#This example code is a technique I use in a library that connects with websites to gather data

ConnectErrs  = (URLError, SSLError, SocketTimeoutError, BadStatusLine, ConnectionResetError)

def connect(url, data):
    #do connection and return some data

def some_function(var_a, var_b, ...):
    try: o = connect(url, data)
    except ConnectErrs as e:
        #do the recovery stuff
    blah #do normal stuff you would do if no exception occurred


  1. If you, also, need to catch other exceptions than those in the pre-defined tuple, you will need to define another except block.

  2. If you just cannot tolerate a global variable, define it in main() and pass it around where needed...

@M.Usman 2017-08-17 11:56:07

One of the way to do this is..

   You do your operations here;
except(Exception1[, Exception2[,...ExceptionN]]]):
   If there is any exception from the given exception list, 
   then execute this block.
   If there is no exception then execute this block. 

and another way is to create method which performs task executed by except block and call it through all of the except block that you write..

   You do your operations here;
except Exception1:
except Exception2:
except Exception3:
   If there is no exception then execute this block. 

def functionname( parameters ):
   //your task..
   return [expression]

I know that second one is not the best way to do this, but i'm just showing number of ways to do this thing.

@majikman 2019-07-02 03:11:29

I'm using the second one because I have two different exceptions that each need to be processed differently. Is there something wrong with doing it that way?

@Eponymous 2019-08-13 19:29:54

@majikman The second method with multiple clauses each calling the same function is not the best when you're trying to not repeat yourself and doing the same thing for two exceptions. (See the other answers for the right way to do that). However, having multiple except clauses is normal when you want to handle the exceptions differently.

@fedorqui 'SO stop harming' 2014-10-30 10:01:18

From Python documentation -> 8.3 Handling Exceptions:

A try statement may have more than one except clause, to specify handlers for different exceptions. At most one handler will be executed. Handlers only handle exceptions that occur in the corresponding try clause, not in other handlers of the same try statement. An except clause may name multiple exceptions as a parenthesized tuple, for example:

except (RuntimeError, TypeError, NameError):

Note that the parentheses around this tuple are required, because except ValueError, e: was the syntax used for what is normally written as except ValueError as e: in modern Python (described below). The old syntax is still supported for backwards compatibility. This means except RuntimeError, TypeError is not equivalent to except (RuntimeError, TypeError): but to except RuntimeError as TypeError: which is not what you want.

Related Questions

Sponsored Content

39 Answered Questions

[SOLVED] How do I check whether a file exists without exceptions?

33 Answered Questions

[SOLVED] How do you assert that a certain exception is thrown in JUnit 4 tests?

28 Answered Questions

[SOLVED] How to read a file line-by-line into a list?

17 Answered Questions

[SOLVED] Why catch and rethrow an exception in C#?

7 Answered Questions

[SOLVED] Manually raising (throwing) an exception in Python

  • 2010-01-12 21:07:40
  • 1645348 View
  • 2139 Score
  • 7 Answer
  • Tags:   python exception

32 Answered Questions

[SOLVED] The case against checked exceptions

10 Answered Questions

[SOLVED] Can I catch multiple Java exceptions in the same catch clause?

28 Answered Questions

[SOLVED] Catch multiple exceptions at once?

9 Answered Questions

[SOLVED] Proper way to declare custom exceptions in modern Python?

8 Answered Questions

[SOLVED] About catching ANY exception

Sponsored Content