Python: 使用多个几乎相同代码的try-except
我在下面的代码中有类似的情况,里面有多个except语句,而这些语句都需要执行someCleanUpCode()这个函数。我在想有没有更简洁的方法来处理这个问题。比如说,能不能有一个只在发生异常时执行的代码块。我不能使用finally块,因为即使没有错误,finally块也会被执行。而我只想在发生错误时才执行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()
2 个回答
1
你是在找像这样的东西吗?
try:
1/0
except (ValueError, ZeroDivisionError) as e:
print e
# add some cleanup code here
>>>integer division or modulo by zero
这个可以捕捉多个异常情况
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()