Python在嵌套try中引发异常

时间:2014-08-07 13:58:22

标签: python exception exception-handling try-catch

我尝试了一个嵌套的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行),然后继续并最终返回。我希望它在加注时能够突破,但不会被其他人抓住。它仍然需要捕获CustomException,如果它发生在' #do更多东西'并继续。

2 个答案:

答案 0 :(得分:2)

如何更改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

答案 1 :(得分:1)

只需编写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