2

How can I better write the following snippet in Python:

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

Just to be clear, I want to execute two codeblocks when the first exception occurs, while only the latter of these two codeblocks when the second exception occurs.

1
  • 3
    Why not extract codeblock-2 into a function, and call it? Commented May 14, 2015 at 10:39

2 Answers 2

5

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

  1. Extract codeblock-2 into a function and just call it (you repeat only one line this way); or
  2. Catch both exceptions in the same except, then handle the two cases appropriately by checking the type of the caught exception.

Note that these aren't 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
Sign up to request clarification or add additional context in comments.

6 Comments

What if the it weren't codeblocks and just oneliners? Thanks for the 2nd option though!
@Deepak if you only have one line for each case, then use option 2 and don't bother extracting the function.
I disagree, there is no difference between "block" and "oneliner". We use function not to save lines.
@VadimPushtaev as some point, you have to have the lines rather than another function call! Obviously, if writing the lines leads to duplication, you should extract a function. But if you have a single line to deal with that case, why would you extract it to a single-line function that's only called from one place?
@jonrsharpe, there are number of reasons. E. g. to give this action a name.
|
1

I would just straightforwardly use local function:

def exception_reaction():
    codeblock2()

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.