[Tutor] Exception Handling

Alan Gauld alan.gauld at btinternet.com
Mon Dec 29 10:10:45 CET 2008

"bob gailer" <bgailer at gmail.com> wrote

> Also IMHO it is bad design to put a lot of code inside a try block. 
> In this case the user might make a mistake on day and then is forced 
> to reenter the year and month!

Obviously there is no absolute rule here but I disagree.
One of the biggest advantages of try/except error handling is
that it keeps the mess of handling errors out of the main logic
of the code. This has two effects:
1) Code that is much easier to read
2) a lot less error handling code

Using "big bite" try/except does mean the except clauses
become more complex if you want to find out exactly which
line caused the error, as in the example above, but it can
be done by examining the traceback, but in general I much
prefer to wrap logical blocks of code using try/except rather
than only one or two lines

> Better to write a function for requesting an integer from the user 
> which loops until the user gets it right (with some way to escape if 
> he gets frustrated and just wants to quit.

And this I agree with. If you do want to check each line use a 
that incorporates the checking within it and call that to get a 
result. And that keeps both Bob and I happy with the try/excepts
stylistically speaking :-)

Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list