5

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
ezdazuzena
  • 6,120
  • 6
  • 41
  • 71
  • you can catch the exception, assign it to a previously defined None variable and then reraise it in finally: Bit trickier to get working in python 3 than 2, i’ll post it later. useful to close resources but still throw the exception – JL Peyret Nov 22 '18 at 21:27

1 Answers1

2

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

Sam Mason
  • 15,216
  • 1
  • 41
  • 60