Python reraise/recatch exception
Asked Answered
J

4

21

I would like to know if it is possible in python to raise an exception in one except block and catch it in a later except block. I believe some other languages do this by default.

Here is what it would look like"

try:
   something
except SpecificError as ex:
   if str(ex) = "some error I am expecting"
      print "close softly"
   else:
      raise
except Exception as ex:
   print "did not close softly"
   raise

I want the raise in the else clause to trigger the final except statement.

In actuality I am not printing anything but logging it and I want to log more in the case that it is the error message that I am not expecting. However this additional logging will be included in the final except.

I believe one solution would be to make a function if it does not close softly which is called in the final except and in the else clause. But that seems unnecessary.

Josi answered 9/6, 2011 at 21:51 Comment(0)
E
20

Only a single except clause in a try block is invoked. If you want the exception to be caught higher up then you will need to use nested try blocks.

Expressly answered 9/6, 2011 at 21:54 Comment(0)
R
22

What about writing 2 try...except blocks like this:

try:
    try:
       something
    except SpecificError as ex:
       if str(ex) == "some error I am expecting"
          print "close softly"
       else:
          raise ex
except Exception as ex:
   print "did not close softly"
   raise ex
Raffle answered 9/6, 2011 at 21:56 Comment(1)
For Python after 2.6 this should be except SpecificError as ex: See #2536260 for comma versus as.Orndorff
E
20

Only a single except clause in a try block is invoked. If you want the exception to be caught higher up then you will need to use nested try blocks.

Expressly answered 9/6, 2011 at 21:54 Comment(0)
R
1

As per python tutorial there is one and only one catched exception per one try statement. You can find pretty simple example in tutorial that will also show you how to correctly use error formatting.

Anyway why do you really need second one? Could you provide more details on this?

Raye answered 9/6, 2011 at 21:59 Comment(0)
G
0

You can do this using the six package.

Six provides simple utilities for wrapping over differences between Python 2 and Python 3.

Specifically, see six.reraise:

Reraise an exception, possibly with a different traceback. In the simple case, reraise(*sys.exc_info()) with an active exception (in an except block) reraises the current exception with the last traceback. A different traceback can be specified with the exc_traceback parameter. Note that since the exception reraising is done within the reraise() function, Python will attach the call frame of reraise() to whatever traceback is raised.

Gadgeteer answered 3/7, 2018 at 19:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.