Dee*_*pak 2 python optimization try-catch
我怎样才能更好地在Python中编写以下代码段:
try:
statement-1
except Exception1:
codeblock-1
codeblock-2
except Exception2:
codeblock-2
Run Code Online (Sandbox Code Playgroud)
为了清楚起见,我想在第一个异常发生时执行两个代码块,而在发生第二个异常时只执行这两个代码块中的后一个.
正如我所看到的,你有两种选择; 之一:
codeblock-2到一个函数,然后调用它(这样只重复一行); 要么except,然后通过检查捕获的异常的类型来适当地处理这两种情况.请注意,这些不是互斥的,如果与第一种方法结合使用,第二种方法可能更具可读性.后者的片段:
try:
statement-1
except (Exception1, Exception2) as exc:
if isinstance(exc, Exception1):
codeblock-1
codeblock-2
Run Code Online (Sandbox Code Playgroud)
在行动:
>>> 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
Run Code Online (Sandbox Code Playgroud)