What is the point of re-raising exceptions?

心不动则不痛 提交于 2019-12-30 11:35:16

问题


So I've seen mention elsewhere of using the following to re-raise an exception.

try:
    whatever()
except:
    raise

What is the purpose re-raising an exception? Surely an uncaught exception will just raise to the top anyway? i.e:

try:
    int("bad")
except:
    raise

has identical output to:

int("bad")

i.e. I get a ValueError in the console.


回答1:


Imagine the following code.

A little setup: You are responsible for maintaining a huge database of information for example, and any loss of data would be catastrophic!

huge_dictionary = {'lots_of_important':['stuffs']}
try:
    check_data(new_data) #make sure the data is in the correct format
    huge_dictionary['lots_of_important'].append(new_data)
except:
    data_writer.backup(huge_dictionary)
    data_writer.close()
    #and any other last second changes
    raise



回答2:


Your example code is pointless, but if you wanted to perform logging or cleanup that only occurs on failure, you could put that between the except: and the raise and you'd do that work and then proceed as if the original exception was bubbling normally.



来源:https://stackoverflow.com/questions/39143878/what-is-the-point-of-re-raising-exceptions

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