error handling

John Machin sjmachin at lexicon.net
Thu Aug 10 20:55:22 EDT 2006


Chris wrote:
> I want to handle errors for a program i'm building in a specific way,
> but I don't want to use try/except/finally because it requires forming
> new blocks of code. I want to be able things like this:
>
> a = [2, 423, "brownie", 234.34]
> try: a[890]
> except IndexError: # I don't use 'finally' here because I specifically
> want to check for an IndexError
>      sys.exit("That number is way too big!")
>
> But sometimes you can have too many of these statements in your
> program, and it starts to get tangled and nasty looking. Is there a way
> I can modify sys.error so that when the interpreter comes accross an
> IndexError it prints "That number is way too big!" before it exits?

Call me crazy, but I don't think convoluted mucking about to produce
"That number is way too big!" -- especially when it could be negative
(way too small) -- is better than doing nothing (no try/except at all)
and getting "list index out of range":

#>>> a = [1,42, 666]
#>>> a[890]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
IndexError: list index out of range
#>>>

Although the manual says "In particular, sys.exit("some error message")
is a quick way to exit a program when an error occurs." this is
scarcely to be recommended. You should at the very least produce a
stack trace so that you can see *where* the error occurred.

<rant>
If you are interacting with a user, you need to give feedback for
*expected* problems like invalid input as close to the point of error
as possible -- online: validate the input before attempting to use it;
batch -- validate it and give feedback which pinpoints the problem (and
it may be required to identify all problems, not just bail out on
seeing the first puff of flak). If it is for your own use: do yourself
a favour and treat yourself like a customer should be treated. You
should have traps for *unexpected* exceptions that likewise pinpoint
what was happening when the exception occurred.

Consider dumping salient info to a file before pulling the ripcord --
that way you don't have to rely on users reporting what they thought
they saw before hitting the power button. Time passing has not meant
progress; user memory capacity has not increased and the usual
cycle-power response time is worse; rebooting a PC takes way longer
than rebooting a green-screen terminal :-)
</rant>

HTH,
John




More information about the Python-list mailing list