我怎样才能更好地用 Python 编写以下代码段:
try:
statement-1
except Exception1:
codeblock-1
codeblock-2
except Exception2:
codeblock-2
明确一点,我想在第一个异常发生时执行两个代码块,而在第二个异常发生时只执行这两个代码块中的后者。
最佳答案
在我看来,您有两个选择;要么:
- 将
codeblock-2
提取到一个函数中并调用它(这样你只需要重复一行);或 - 在同一个
except
中捕获这两个异常,然后通过检查捕获的异常的类型来适本地处理这两种情况。
请注意,这些并不相互排斥,如果将第二种方法与第一种结合使用,则第二种方法可能更具可读性。后者的一个片段:
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 - Python中如何用冗余代码更好地编写多个异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30235188/