如何在Python中重新捕获已捕获的异常?

时间:2017-07-28 17:16:27

标签: python python-2.7

我有类似以下的代码:

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 - 部分内部重新引发异常并在第二个except部分内再次捕获它。

怎么做?

3 个答案:

答案 0 :(得分:7)

Python的语法无法在同一个except上从一个try块继续到另一个块。最接近的是两个try s:

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

就个人而言,我会使用一个except块并手动执行调度:

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

答案 1 :(得分:0)

这是你在找什么?

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

答案 2 :(得分:-1)

您只需使用raise关键字来引发刚刚捕获的错误。

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