Python reraise/recatch exception

天大地大妈咪最大 提交于 2019-12-09 14:39:57

问题


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.


回答1:


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.




回答2:


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



回答3:


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?




回答4:


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.



来源:https://stackoverflow.com/questions/6299756/python-reraise-recatch-exception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!