我在下面的代码中有类似的东西,我有多个except语句,所有这些都必须执行someCleanUpCode()函数。我想知道是否有更短的方法来做到这一点。就像只有在发生异常时才执行的块一样。我不能使用finally块,因为当try没有引发错误时也会执行。我只需要在出现错误时执行someCleanUpCode()。我首先要打印错误,然后运行someCleanUpCode()
try:
dangerousCode()
except CalledProcessError:
print "There was an error without a message"
someCleanUpCode()
except Exception as e:
print "There was an error: " +repr(e)
someCleanUpCode()
答案 0 :(得分:1)
try:
1/0
except (ValueError, ZeroDivisionError) as e:
print e
# add some cleanup code here
>>>integer division or modulo by zero
这会捕获多个例外
答案 1 :(得分:1)
假设CalledProcessorError
子类Exception
(应该是这种情况):
try:
dangerous_code()
except Exception as e:
print "There was an error %s" % ("without an error" if isinstance(e, CalledProcessError) else repr(e))
some_cleanup_code()
或者如果您还有更多工作要做:
try:
dangerous_code()
except Exception as e:
try:
dangerous_code()
except Exception as e:
if isinstance(e, CalledProcessError):
print "There was an error without a message"
else:
print "There was an error: " +repr(e)
some_cleanup_code()