Python reraise/recatch exception

Aaron Robinson picture Aaron Robinson · Jun 9, 2011 · Viewed 13.6k times · Source

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.

Answer

badzil picture badzil · Jun 9, 2011

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