如何在Python中用冗余代码更好地编写多个异常?
How to better write multiple exceptions with redundant code in Python?
我怎样才能更好地在 Python 中编写以下代码段:
try:
statement-1
except Exception1:
codeblock-1
codeblock-2
except Exception2:
codeblock-2
明确一点,我想在第一个异常发生时执行两个代码块,而在第二个异常发生时只执行这两个代码块中的后者。
我会直接使用局部函数:
def exception_reaction():
codeblock2()
try:
statement1()
except Exception1:
codeblock1()
exception_reaction()
except Exception2:
exception_reaction()
在我看来,你有两个选择;或者:
- 将
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 中编写以下代码段:
try:
statement-1
except Exception1:
codeblock-1
codeblock-2
except Exception2:
codeblock-2
明确一点,我想在第一个异常发生时执行两个代码块,而在第二个异常发生时只执行这两个代码块中的后者。
我会直接使用局部函数:
def exception_reaction():
codeblock2()
try:
statement1()
except Exception1:
codeblock1()
exception_reaction()
except Exception2:
exception_reaction()
在我看来,你有两个选择;或者:
- 将
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