error handling
Steven D'Aprano
steve at REMOVEME.cybersource.com.au
Thu Aug 10 21:57:47 EDT 2006
On Thu, 10 Aug 2006 16:59:56 -0700, Farshid Lashkari wrote:
> Chris wrote:
>> 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?
>
> Hi,
>
> Try placing the try/except block around the main function of your program:
>
> if __name__ == '__main__':
> try:
> main()
> except IndexError:
> sys.exit("That number is way too big!")
That's broken.
Imagine that somewhere in main() the following is called:
D = {"a": "apple", "b": "bicycle", "c": "cat"}
print D["aardvark"]
Your code now prints "That number is way too big!". That's not good.
try...except blocks should, as a general rule, cover only the smallest
amount of code that they need to.
One possible solution is to use a custom class:
# untested
class MyList(list):
def __getitem__(self, i):
if i >= len(self):
raise IndexError("That index is too big!")
super(list, self).__getitem__(i)
Another is a helper function:
def safe_getindex(somelist, i):
if i >= len(somelist):
raise IndexError("That index is too big!")
return somelist[i]
You can of course re-write them to use a try...except block instead of
testing the index.
--
Steven D'Aprano
More information about the Python-list
mailing list