[Tutor] Exception Handling

Lie Ryan lie.1296 at gmail.com
Tue Dec 30 13:59:36 CET 2008


On Mon, 29 Dec 2008 16:57:44 +0100, spir wrote:

> On Mon, 29 Dec 2008 09:10:45 -0000
> "Alan Gauld" <alan.gauld at btinternet.com> wrote:
> 
> 
>> "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
>  
> I often use the else clause of try...except. This allows putting only
> the minimum problematic code lines inside the try block, which is good
> both for legibility andto avoid catching unexpected errors. The else
> will be executed only in case of no exception:

I think it's better to put less in a try-clause so I'd rather not catch 
errors on the raw_input, and put validation code in a function, which I'd 
enclose in a try block, like this:

while True:
    yr = raw_input("What year were you born? ")
    mn = raw_input("What month were you born? ")
    dy = raw_input("What day were you born? ")
    
    try:
        date = is_valid_date(yr, mn, dy)
    except InvalidDate, e:
        # e might contain input not a number, or there is no 31 february
        print 'You entered an Invalid Date: ', e
    else:
        do_things(date)

Also, I'd rather ask for the dates in one raw_input, cuts much of the 
mess for the user (although it's a bit of extra codes)



More information about the Tutor mailing list