简体   繁体   中英

How to re-catch already caught exception in Python?

I have a code similar to the following:

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)

Where DerivedException is derived from BaseException .

So, like the comment in the code mentions - I want to re-raise the exception from inside of the first except -section and catch it again inside the second except -section.

How to do that?

Python's syntax provides no way to continue from one except block to another on the same try . The closest you can get is with two 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)

Personally, I'd use one except block and do the dispatch manually:

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

Is this what you are looking for?

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

You just use the raise keyword alone to raise the error that was just caught.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM