Can a block finally know if an exception has occurred

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 design 'value' in locals()seems a little fragile, and I wonder if there is a better way to do this.

I really want the code inside finallyto behave a little differently, depending on whether the block raised an tryexception. Is there any way to find out if an exception was thrown?

+4
source share
3 answers

If the goal is β€œwhen the exception was thrown, do something else”, 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 have a few exceptions with which you are really doing something, I would 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)
+3

:

:

value = None
try:
    value = my_function(*args)
finally:
    with some_context_manager:
        do_something()
        if value is not None:
            do_something_else(value)

:

try:
    value = my_function(*args)
except:
    value = None
    raise
finally:
    with some_context_manager:
        do_something()
        if value is not None:
            do_something_else(value)
+1

Assign the exception to a variable in the except package, and then use it in the finally package.

foo = False
try:
    raise KeyError('foo not found')
except KeyError as e:
    pprint(e)
    foo = e
finally:
    if foo:
        print(foo)
    else:
        print('NO')
-1
source

Source: https://habr.com/ru/post/1674424/


All Articles