如何在Python中使用冗余代码更好地编写多个异常? [英] How to better write multiple exceptions with redundant code in Python?

查看:112
本文介绍了如何在Python中使用冗余代码更好地编写多个异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何更好地用Python编写以下代码段:

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.

推荐答案

如我所见,您有两个选择;要么:

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

  1. codeblock-2提取到函数中,然后调用它(您只重复一行).或
  2. 在同一个except中捕获这两个异常,然后通过检查捕获的异常的类型来适当地处理这两种情况.
  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

实际情况:

>>> 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

这篇关于如何在Python中使用冗余代码更好地编写多个异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆