[英]I have a python file with multiple exception for each block , I need to utest for the same . Is there any approach to cover all exceptions at one go?
[英]Python exceptions: call same function for any Exception
请注意,在下面的代码中,如果抛出任何异常,则调用foobar()
。 有没有办法在不使用每个Exception中的相同行的情况下执行此操作?
try:
foo()
except(ErrorTypeA):
bar()
foobar()
except(ErrorTypeB):
baz()
foobar()
except(SwineFlu):
print 'You have caught Swine Flu!'
foobar()
except:
foobar()
success = False
try:
foo()
success = True
except(A):
bar()
except(B):
baz()
except(C):
bay()
finally:
if not success:
foobar()
您可以使用字典将异常映射到要调用的函数:
exception_map = { ErrorTypeA : bar, ErrorTypeB : baz }
try:
try:
somthing()
except tuple(exception_map), e: # this catches only the exceptions in the map
exception_map[type(e)]() # calls the related function
raise # raise the Excetion again and the next line catches it
except Exception, e: # every Exception ends here
foobar()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.