我需要更新一個物件的一個屬性,以進行一次驗證。我需要在任何情況下,在驗證引發錯誤之前恢復該屬性。
我目前很困惑,這是否是在例外產生之前恢復的最漂亮的方法,因為這樣我就必須重復恢復的代碼了。
finally在這里不起作用,因為它是在 raise 陳述句之后執行的。
amount = instance.quantity
instance.quantity = 0
try:
validate_instance(instance)
except 例外。
instance.amount = amount
提高。
else:
instance.amount = amount
uj5u.com熱心網友回復:
最后塊應該沒問題了,如下圖所示:
amount = 15。
def throw_me_an_error()。
try:
amount = 20.
print("我已經把金額設定為20。")
test = 'hey' 1
except Exception as e:
print('Exception thrown'/span>)
raise e
else:
print('Else part')
finally:
金額=15。
print('I reverted the amount to 15.' )
print('終于!')
try:
throw_me_an_error()
except 例外。
print('An exception was thrown')
print(f'The amount is now {amount}')
結果是
我已經將金額設定為20。
拋出的例外
我把金額恢復到了15。
最后!
拋出了一個例外
現在的金額是15
uj5u.com熱心網友回復:
正如其他答案中指出的那樣,最后的作業確實很好:
try。
try:
print(1)
x = 1
3
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/323180.html
標籤:
