还原 python 中的更改 try exception block before raising
Revert changes in python try exception block before raising
我需要为单个验证更新对象的一个属性。在任何情况下,我都需要在验证引发错误之前恢复它。
我目前很困惑,如果这实际上是在异常引发之前恢复某些东西的最漂亮的方法,因为那时我必须复制恢复代码。
finally
在这里不起作用,因为它是在 raise 语句之后执行的。
amount = instance.amount
instance.amount = 0
try:
validate_instance(instance)
except Exception:
instance.amount = amount
raise
else:
instance.amount = amount
最后block应该就可以了,如下图:
amount = 15
def throw_me_an_error():
try:
amount = 20
print("I've set the amount to 20.")
test = 'hey' + 1
except Exception as e:
print('Exception thrown')
raise e
else:
print('Else part')
finally:
amount = 15
print('I reverted the amount to 15.')
print('Finally!')
try:
throw_me_an_error()
except Exception:
print('An exception was thrown')
print(f'The amount is now {amount}')
结果
I've set the amount to 20.
Exception thrown
I reverted the amount to 15.
Finally!
An exception was thrown
The amount is now 15
正如其他答案中指出的那样,最终确实可以正常工作:
>>> try:
... try:
... print(1)
... x += 1
... except Exception:
... raise
... finally:
... print(2)
... except Exception:
... print(3)
...
1
2
3
我需要为单个验证更新对象的一个属性。在任何情况下,我都需要在验证引发错误之前恢复它。
我目前很困惑,如果这实际上是在异常引发之前恢复某些东西的最漂亮的方法,因为那时我必须复制恢复代码。
finally
在这里不起作用,因为它是在 raise 语句之后执行的。
amount = instance.amount
instance.amount = 0
try:
validate_instance(instance)
except Exception:
instance.amount = amount
raise
else:
instance.amount = amount
最后block应该就可以了,如下图:
amount = 15
def throw_me_an_error():
try:
amount = 20
print("I've set the amount to 20.")
test = 'hey' + 1
except Exception as e:
print('Exception thrown')
raise e
else:
print('Else part')
finally:
amount = 15
print('I reverted the amount to 15.')
print('Finally!')
try:
throw_me_an_error()
except Exception:
print('An exception was thrown')
print(f'The amount is now {amount}')
结果
I've set the amount to 20.
Exception thrown
I reverted the amount to 15.
Finally!
An exception was thrown
The amount is now 15
正如其他答案中指出的那样,最终确实可以正常工作:
>>> try:
... try:
... print(1)
... x += 1
... except Exception:
... raise
... finally:
... print(2)
... except Exception:
... print(3)
...
1
2
3