I need to update one attribute of an object for a single validation. I need to revert that in any case and before the Validation raises an error.
I'm currently confused if this is actually the most beautiful way to revert something before the Exception raises because then I have to duplicate the revert code.
finally
does not work here as it is executed after the raise statement.
amount = instance.amount
instance.amount = 0
try:
validate_instance(instance)
except Exception:
instance.amount = amount
raise
else:
instance.amount = amount
CodePudding user response:
Finally block should be fine, as shown below:
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}')
results in
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
CodePudding user response:
As pointed out in the other answers, finally works indeed fine:
>>> try:
... try:
... print(1)
... x = 1
... except Exception:
... raise
... finally:
... print(2)
... except Exception:
... print(3)
...
1
2
3