Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a finally block know if there was an exception

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?

like image 565
kasperd Avatar asked Oct 18 '22 14:10

kasperd


1 Answers

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)
like image 66
mwchase Avatar answered Oct 21 '22 03:10

mwchase