Search code examples
pythonexceptiontry-except

python exception not raised if finally returns value


Can anyone explain why the following example does not raise the Exception?

def foo():
    try:
        0/0
    except Exception:
        print('in except')
        raise
    finally:
        print('in finally')
        return 'bar'

my_var = foo()
print(my_var)

This just returns:

in except
in finally
bar

Where as the same code without the return 'bar' statement throws the exception:

in except
in finally
Traceback (most recent call last):
  File "test.py", line 10, in <module>
    my_var = foo()
  File "test.py", line 3, in foo
    0/0
ZeroDivisionError: division by zero

Solution

  • see https://stackoverflow.com/a/19805813/1358308 for more detail, but in brief

    the finally block should always be executed, Python therefore has to ignore the raise statement as that would violate semantics