【问题标题】:Python raise exception within nested tryPython在嵌套尝试中引发异常
【发布时间】:2014-08-07 13:58:21
【问题描述】:

我在 try 中有一个嵌套的 try/except 块,我想引发错误,然后从方法中中断,但它会继续。

try:
    #stuff
    try:
        #do some stuff
    except:
        raise CustomException('debug info')
    #do some more stuff
except CustomException:
    #stuff
#do even more stuff
return stuff

目前,在引发 CustomException(第 5 行)之后,它会跳转到 except(第 7 行),然后继续并最终返回。我希望它在加注时打破,但不要被例外抓住。如果它发生在“#do some more stuff”中,它仍然需要捕获 CustomException 并继续。

【问题讨论】:

  • 您基本上是在引发异常并立即捕获它。没有意义,当然会继续。如果你想“脱离方法”,你必须让异常离开你的方法,而不是抓住它。
  • 使用不同的异常类怎么样?

标签: python exception exception-handling try-catch


【解决方案1】:

如何改变try-except的结构如下?

try:
    #do some stuff
except:
    raise CustomException('debug info')
try:
    #do some more stuff
except CustomException:
    #stuff
#do even more stuff
return stuff

【讨论】:

  • 糟糕,忘记添加#do stuff
  • @SirDeimos,除了 stuffdo some stuffdo some more stuff.
【解决方案2】:

只需写raise,重新引发捕获的异常。

try:
    #stuff
    try:
        #do some stuff
    except:
        raise CustomException('debug info')
    #do some more stuff
except CustomException:
    #stuff
    raise  ## KM: This re-raise the exception

## KM: This wont be executed if CustomException('debug info') was raised
#do even more stuff

return stuff

【讨论】:

    猜你喜欢
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-14
    相关资源
    最近更新 更多