开发者

Python reraise/recatch exception

开发者 https://www.devze.com 2023-03-12 08:28 出处:网络
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.

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 messa开发者_开发知识库ge 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.


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


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.


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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消