3

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?

1
  • I think you need to nest another try-except, because the first try-except will not catch again. Commented Jul 28, 2017 at 17:22

3 Answers 3

7

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 trys:

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()
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

-1

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)

2 Comments

But an error that is raised in one except will not be caught in any of the excepts that follow it.
oh then you just need to add another try block around it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.