[Tutor] code review please

Kent Johnson kent37 at tds.net
Wed Dec 28 14:00:22 CET 2005


Danny Yoo wrote:
> Similarly, the try/except for IndexError seems too pervasive: rather than
> wrap it around the whole program, we may want to limit its extent to just
> around the sys.argv access.  Otherwise, any other IndexError has the
> potential of being misattributed.  Much of the program does indexing of
> some sort, so that's why this concerns me.
> 
> Alternatively, doing the explicit length check:
> 
>    if not sys.argv[1:]:
>        print some kind of usage message
>        raise SystemExit
> 
> might be sufficient.
> 
> 
> Unless we really want to hide errors from the user, I'd avoid the
> exception handlers altogether: if bad things happen, the default exception
> handler gives a fairly good stack trace that aids debugging.
> 
> But if we do want to handle the exceptions manually, we should try to make
> sure that useful information is preserved in the error messages: it's a
> terrible thing to get an error message that says "Something bad happened."
> when we can do much better.  *grin*

I agree with Danny that in this case there is no need to catch the 
exceptions - just let the default exception handler do its thing.

If you *do* want to handle the exceptions yourself, a good principle is 
to put the try / except around the least amount of code possible - just 
the lines that may generate the expected exception. This prevents the 
except clause from hiding unexpected exceptions.

An easy way to do this is to use try / except / else. The else clause is 
only executed if no exception was caught by the except clause. In your 
case you could write

try:
   fname = sys.argv[1]
except IndexError:
   # report the error as you like
else:
   # normal processing goes here

Kent



More information about the Tutor mailing list