谁能帮我处理下面的代码:
try:
#do some things
myClass.close()
except Exception, error:
myClass.close()
raise error
如你所见,我不能在这里使用finally
,因为那样的话我将不知道是否真的发生了错误,我需要引发这个错误(raise error)
我的问题是如何避免使用这两次 myClass.close()?
在此先感谢您的帮助
最佳答案
这等同于您的代码:
try:
#do some things
finally:
myClass.close()
首先它调用 myClass.close()
,如果出现错误,它会再次引发。
你也可以用它来处理特定的异常:
try:
#do some things
except Exception, error:
raise # re-raise the original exception
finally:
myClass.close()
关于python - python中令人毛骨悚然的设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7379596/