Catch multiple exceptions in one line (except block)
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Magical Minnie Puzzles
--
Chapters
00:00 Catch Multiple Exceptions In One Line (Except Block)
00:49 Accepted Answer Score 5116
01:18 Answer 2 Score 532
03:42 Answer 3 Score 74
04:39 Answer 4 Score 61
05:19 Answer 5 Score 34
05:49 Thank you
--
Full question
https://stackoverflow.com/questions/6470...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #exception #exceptionhandling
#avk47
ACCEPTED ANSWER
Score 5127
From Python Documentation:
An except clause may name multiple exceptions as a parenthesized tuple, for example
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
Or, for Python 2 only:
except (IDontLikeYouException, YouAreBeingMeanException), e:
    pass
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.
ANSWER 2
Score 533
How do I catch multiple exceptions in one line (except block)
Do this:
try:
    may_raise_specific_errors():
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
try:
    mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
    sys.exit(0)
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: https://docs.python.org/tutorial/errors.html
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
try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)
Note that in Python 3, the err object falls out of scope when the except block is concluded.
Deprecated
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
try:
    mainstuff()
except (KeyboardInterrupt, EOFError), err: # don't do this in Python 2.6+
    print err
    print err.args
    sys.exit(0)
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:
try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass
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):
     do_something()
So when you want to pass on certain exceptions, use suppress.
ANSWER 3
Score 75
From Python documentation -> 8.3 Handling Exceptions:
A
trystatement 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): passNote that the parentheses around this tuple are required, because except
ValueError, e:was the syntax used for what is normally written asexcept ValueError as e:in modern Python (described below). The old syntax is still supported for backwards compatibility. This meansexcept RuntimeError, TypeErroris not equivalent toexcept (RuntimeError, TypeError):but toexcept RuntimeError asTypeError:which is not what you want.
ANSWER 4
Score 34
One of the way to do this is..
try:
   You do your operations here;
   ......................
except(Exception1[, Exception2[,...ExceptionN]]]):
   If there is any exception from the given exception list, 
   then execute this block.
   ......................
else:
   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..
try:
   You do your operations here;
   ......................
except Exception1:
    functionname(parameterList)
except Exception2:
    functionname(parameterList)
except Exception3:
    functionname(parameterList)
else:
   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.