24

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()
wim
  • 338,267
  • 99
  • 616
  • 750
  • 6
    duplicate of [return eats exception](http://stackoverflow.com/questions/517060/return-eats-exception) – gecco Dec 20 '11 at 12:04

1 Answers1

35

From the Python documentation:

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

interjay
  • 107,303
  • 21
  • 270
  • 254
  • 2
    interesting! where does it 'go', if that question even makes sense? – wim Dec 20 '11 at 12:33
  • 10
    @wim: It goes wherever local variables go at the end of the function, I suppose. One way to look at it is that the exception is re-raised at the end of the `finally` block. Since the `return` skips the rest of the `finally` block, re-raising the exception never happens. – interjay Dec 20 '11 at 12:46