Python:使用几乎相同的代码尝试使用多个例外捕获
我在下面的代码中有类似的东西,我有多个except语句,它们都必须执行someCleanUpCode()函数。我想知道是否有一个较短的方法来做这件事。就像一个只有在出现异常时才执行的块。我不能使用finally块,因为当try没有引发错误时,也会执行finally块。我只需要在出现错误时执行someCleanUpCode()。我首先要打印错误,然后运行someCleanUpCode()Python:使用几乎相同的代码尝试使用多个例外捕获,python,try-catch,except,Python,Try Catch,Except,我在下面的代码中有类似的东西,我有多个except语句,它们都必须执行someCleanUpCode()函数。我想知道是否有一个较短的方法来做这件事。就像一个只有在出现异常时才执行的块。我不能使用finally块,因为当try没有引发错误时,也会执行finally块。我只需要在出现错误时执行someCleanUpCode()。我首先要打印错误,然后运行someCleanUpCode() 你在找这样的东西吗 try: 1/0 except (ValueError, ZeroDivision
你在找这样的东西吗
try:
1/0
except (ValueError, ZeroDivisionError) as e:
print e
# add some cleanup code here
>>>integer division or modulo by zero
这将捕获多个异常假设
调用的处理器错误
子类异常(应为这种情况):
或者,如果您还有更多工作要做:
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()
我不知道还有什么其他方法可以做到这一点。我认为当前的代码很好-它清楚地表明,在每个错误情况下都会调用
someCleanUpCode
。好的,我将继续使用该代码;)假设危险代码总是一个函数,并且你有很多这样的函数,你可能想用@foo包装器来包装它,在调用函数时添加try/except例程。但问题是,只有部分代码是共享的。不是所有的代码都是一样的。我明白了,你可以这样做。但当我有两个以上的例外时,这会变得非常混乱:)。但是谢谢你的代码。是的,如果你有六个例外子句,每个子句都有自己的特定内容,那么你当前的结构可能会更干净。。。但它不是干的。
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()