Python在嵌套try中引发异常

Python raise exception within nested try

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

1
2
3
4
5
6
7
8
9
10
11
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 some more stuff'并继续。


怎么样改变try-except的结构如下?

1
2
3
4
5
6
7
8
9
10
try:
    #do some stuff
except:
    raise CustomException('debug info')
try:
    #do some more stuff
except CustomException:
    #stuff
#do even more stuff
return stuff


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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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