[Tutor] Unusual behavior in readline

Alan Gauld alan.gauld at freenet.co.uk
Wed Aug 9 09:42:48 CEST 2006

<CCing back to the list>

>>>You don't need to initialise Entry, the for loop does that for you.
> just a habit- I've always initialized my vars up front.
> so I know they are initialized.

Fair enough, good practice for other languages certainly.

>> >>BTW Why not just put all this stuff in the body of the try?
> Because the try is only setup to catch an IO error.
> If something other than an IOerror were to occur, it would be
> missed unless other exceptions were trapped.

Its missed in the else clause too.
But the else clause adds two extra control structures
(the except and the else) to the code for the reader to
negotiate which significantly impairs comprehension
of the main execution path.

> The most probable is the IOerror, which is why I trapped it.

Which is fine but no reason to put the except clause immediately
after the try line, that just clutters the code block.

>>>You should very rarely need an else clause when using try/except.

> If the exception doesn't happen, then what ?

The code just goes through:

   if False: raise ValueError    # never happens
   print 'hello'
   print 'world'
   print 'this code is pretty safe'
except ValueError: print 'its a mistake!"

No need for an else clause.

> That's what the else clause is for

Nope, the else clause is for a few unusual cases where you
need to do stuff if no exception occurs that is not part of the
main processing. I've only ever seen a real valid use of it
once in dealing with housekeeping of sockets, and even
there a finally block could have been used at the cost of
an extra try statement. The else just kept it a bit tidier.

But else should not be used for mainstream processing.
One of the biggest advantages of try/except handling is that
it removes all the error processing out of the way of the
reader to the bottom of the block. You can just write the
happy path stuff as a continuous sequence without worrying
about error paths. (FWIW This is also the recommended
practice in writing use cases, for the same reasons)

Of course else can be used as you did and the code will
work, but you lose a big advantage of try/except style.

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list