python try-finally

wim picture wim · Dec 20, 2011 · Viewed 7.8k times · Source

Why does the exception in foo whizz by unnoticed, but the exception in bar is raised?

def foo():
    try:
        raise Exception('foo')
    finally:
        return

def bar():
    try:
        raise Exception('bar')
    finally:
        pass

foo()
bar()

Answer

interjay picture interjay · Dec 20, 2011

From the Python documentation:

If the finally clause raises another exception or executes a return or break statement, the saved exception is lost.