If you move the contents of the else block inside the try block, you will also catch exceptions that may occur during the else block. If the line
print(foo.read())
in your example, throws an IOError , your first code snippet will not catch this error, while your second snippet will. You try to keep try blocks as small as possible in general, to really catch only those exceptions that you want to catch.
The finally block is always executed no matter what. If, for example, the try block contains a return , the finally block will still be executed, and any code under the entire try / except block will not.
Sven Marnach May 18 '11 at 10:58 p.m. 2011-05-18 22:58
source share