What's the best way to write multiple redundant exceptions in Python?

What is the best way to write the following snippet in Python:

try:
    statement-1
except Exception1:
    codeblock-1
    codeblock-2
except Exception2:
    codeblock-2

      

To be clear, I want to execute two codeblocks when the first exception occurs, and only the last of these two codeblocks when the second exception occurs.

+2


source to share


2 answers


You have two options, as I see it; or:

  • Extract codeblock-2

    into a function and just call it (this way you only repeat one line); or
  • Catch both exceptions in the same except

    , and then handle the two cases appropriately by checking the type of the infected exception.

Note that they are not mutually exclusive, and the second approach is probably more readable if combined with the first. A snippet of the latter:



try:
    statement-1
except (Exception1, Exception2) as exc:
    if isinstance(exc, Exception1):
        codeblock-1
    codeblock-2

      

In action:

>>> def test(x, y):
    try:
        return x / y
    except (TypeError, ZeroDivisionError) as exc:
        if isinstance(exc, TypeError):
            print "We got a type error"
        print "We got a type or zero division error"


>>> test(1, 2.)
0.5
>>> test(1, 'foo')
We got a type error
We got a type or zero division error
>>> test(1, 0)
We got a type or zero division error

      

+5


source


I would just use a local function:



def exception_reaction():
    codeblock2()

try:
    statement1()
except Exception1:
    codeblock1()
    exception_reaction()
except Exception2:
    exception_reaction()

      

+1


source







All Articles