Python:try-catch,包含几个相同代码的多个例外

时间:2014-07-30 14:23:36

标签: python try-catch except

我在下面的代码中有类似的东西,我有多个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()

2 个答案:

答案 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()