3

Today this interesting piece of python code was posted on Twitter.

def f():
    try:
        raise KeyError
    finally:
        return 42


g = f()

When executing it, f() returns 42 and there's no exception bubbling up the stack as I'd expect. When replacing the return 42 with e.g. as pass statement, the exception propagates outside the function as expected.

However, I wonder why that's not the case when using return. After all, there's still an uncaught exception.

Does this mean that a python function can either raise or return but a return will automatically clear an exception?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636

0 Answers0