In a Python program I have code with the following structure:
try:
value = my_function(*args)
finally:
with some_context_manager:
do_something()
if 'value' in locals():
do_something_else(value)
But the 'value' in locals()
construction feels a bit fragile and I am wondering if there is a better way to do this.
What I really want is for the code inside the finally
to behave slightly different depending on whether the try
block raised an exception. Is there a way to know if an exception was raised?
If the goal is "when an exception was raised, do something different", how about:
exception_raised = False
try:
value = my_function(*args)
except:
exception_raised = True
raise
finally:
with some_context_manager:
do_something()
if not exception_raised:
do_something_else(value)
Now, if you're going to have multiple exceptions that you actually do something with, I'd recommend:
completed_successfully = False
try:
value = my_function(*args)
else:
completed_successfully = True
finally:
with some_context_manager:
do_something()
if completed_sucessfully:
do_something_else(value)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With