【问题标题】:Python: try-catch with multiple excepts with almost identical codePython:使用几乎相同的代码尝试捕获多个异常
【发布时间】:2014-07-30 14:23:36
【问题描述】:

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

【问题讨论】:

  • 我不知道有任何其他方法可以做到这一点。我认为当前的代码很好 - 它清楚地表明在每个错误情况下都会调用 someCleanUpCode
  • 好的,我会坚持使用该代码 ;)
  • 假设危险代码始终是一个函数,并且您有很多,您可能希望使用 @foo 包装器包装它,该包装器在调用该函数时添加 try/except 例程。跨度>

标签: python try-catch except


【解决方案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()

【讨论】:

  • 我明白了,你可以这样做。但是当我有两个以上的例外时,这会变得非常混乱:)。但是感谢这段代码。
  • 是的,如果你有六个 except 子句,每个子句都有自己的特定内容,那么你当前的结构可能更干净......但它不是 DRY。
【解决方案2】:

你在寻找这样的东西吗?

try:
    1/0
except (ValueError, ZeroDivisionError) as e:
    print e
    # add some cleanup code here


>>>integer division or modulo by zero

这会捕获多​​个异常

【讨论】:

  • 但问题是只共享了一部分代码。并非整个代码都是一样的。
猜你喜欢
  • 1970-01-01
  • 2019-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-13
  • 2011-12-05
  • 2014-05-11
  • 2023-03-27
相关资源
最近更新 更多