How do I catch an already caught exception in Python?

I have some 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 it DerivedException

comes from BaseException

.

So, just like the comment in the code is mentioned - I want to re-throw the exception from within the first section except

and catch it again in the second section except

.

How to do it?

+3


source to share


3 answers


Python syntax does not allow you to go from one block except

to another in the same try

. The closest you can get is 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 would use one block except

and manually submit:

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

      

+7


source


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

      

0


source


You simply use the raise keyword to raise the error you just encountered.

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

      

-1


source







All Articles