Programming Python is mostly straightforward. Not thinking, however, can lead to subtle bugs, and this one had me stumped for a while. If a program raises an exception that is not caught further up the call stack, I expect the interpreter to exit with a whimper. Consider the following code:
def throwing_function(): try: print 1 / 0 finally: print "Finally" return "Useful string" print throwing_function()
Running this will print
Finally Useful string
If you can spot the bug immediately, good for you, but I didn’t. I expected this code to fail with a ZeroDivisionError exception. Not so. It turns out that the return statement hides the exception.
The correct code should look like this:
def throwing_function(): try: print 1 / 0 finally: print "Finally" return "Useful string" print throwing_function()
Now it behaves like expected:
Finally Traceback (most recent call last): File "swallowed_exception_fixed.py", line 8, inprint throwing_function() File "swallowed_exception_fixed.py", line 3, in throwing_function print 1 / 0 ZeroDivisionError: integer division or modulo by zero
A good rule of thumb would be to never put a return statement inside a finally clause.
