What is the point of re-raising exceptions?

后端 未结 2 1077
不思量自难忘°
不思量自难忘° 2021-01-14 07:35

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

try:
    whatever()
except:
    raise

What is the purpose

相关标签:
2条回答
  • 2021-01-14 07:56

    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.

    0 讨论(0)
  • 2021-01-14 07:58

    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
    
    0 讨论(0)
提交回复
热议问题