繁体   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