簡體   English   中英

如何在Python中重新捕獲已捕獲的異常?

[英]How to re-catch already caught exception in Python?

我有一個類似於以下代碼:

try:
    something()
except DerivedException as e:
    if e.field1 == 'abc':
        handle(e)
    else:
        # re-raise with catch in the next section!
except BaseException as e:
    do_some_stuff(e)

DerivedException是從BaseException派生的。

所以,就像代碼中提到的注釋一樣 - 我想從第一個except section except重新引發異常,並在第二個except section except再次捕獲它。

怎么做?

Python的語法提供沒有辦法從一個繼續except塊地在同一個try 你可以得到的最接近的是兩個try

try:
    try:
        whatever()
    except Whatever as e:
        if dont_want_to_handle(e):
            raise
        handle(e)
except BroaderCategory as e:
    handle_differently(e)

就個人而言,我會使用exceptexcept一個並手動執行調度:

try:
    whatever()
except BroaderCategory as e:
    if isinstance(e, SpecificType) and other_checks(e):
        do_one_thing()
    else:
        do_something_else()

這是你想要的?

{ ~ }  » python                                                                                     
>>> try:
...     try:
...         raise Exception("foobar")
...     except Exception as e:
...         raise e
... except Exception as f:
...     print "hi"
...
hi

您只需使用raise關鍵字來引發剛剛捕獲的錯誤。

try:
    try:
        something()
    except DerivedException as e:
        if e.field1 == 'abc':
            handle(e)
        else:
            raise
except BaseException as e:
    do_some_stuff(e)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM