How to better write multiple exceptions with redundant code in Python?

谁说我不能喝 提交于 2019-12-11 02:24:39

问题


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:


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



回答2:


I would just straightforwardly use local function:

def exception_reaction():
    codeblock2()

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


来源:https://stackoverflow.com/questions/30235188/how-to-better-write-multiple-exceptions-with-redundant-code-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!