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.

jncraton
  • 9,022
  • 3
  • 34
  • 49
Aaron Robinson
  • 406
  • 1
  • 6
  • 13

4 Answers4

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
jncraton
  • 9,022
  • 3
  • 34
  • 49
badzil
  • 3,440
  • 4
  • 19
  • 27
  • 5
    For Python after 2.6 this should be `except SpecificError as ex:` See http://stackoverflow.com/questions/2535760/python-try-except-comma-vs-as-in-except for comma versus as. – hum3 Sep 30 '15 at 14:32
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.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
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?

Artsiom Rudzenka
  • 27,895
  • 4
  • 34
  • 52
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.

crypdick
  • 16,152
  • 7
  • 51
  • 74