March 18, 2011
Python’s try-except-else-finally Block

Started reading IronPython in Action to get acquainted with my language of choice for Maperitive scripting.

While browsing through the book, I noticed a little gem I complained was missing in C# a few days ago (code stolen from here):

try:
    f = open(arg, 'r')
except IOError:
    print 'cannot open', arg
else:
    print arg, 'has', len(f.readlines()), 'lines'
    f.close()

And the explanation for the else clause:

The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try … except statement.

So it looks like I’m not that crazy afterall…

  1. towsonsiff8404 reblogged this from braincrunch
  2. hcg-diet-canada reblogged this from braincrunch
  3. braincrunch posted this