except clause not catching IndexError
Ben Cartwright
bencvt at gmail.com
Wed Feb 22 12:23:26 EST 2006
Derek Schuff wrote:
> I have some code like this:
> for line in f:
> toks = line.split()
> try:
> if int(toks[2],16) == qaddrs[i]+0x1000 and toks[0] == "200": #producer
> write
> prod = int(toks[3], 16)
> elif int(toks[2],16) == qaddrs[i]+0x1002 and toks[0] == "200":
> #consumer write
> cons = int(toks[3], 16)
> else:
> continue
> except IndexError: #happens if theres a partial line at the end of file
> print "indexerror"
> break
>
> However, when I run it, it seems that I'm not catching the IndexError:
> Traceback (most recent call last):
> File "/home/dschuff/bin/speeds.py", line 202, in ?
> if int(toks[2],16) == qaddrs[i]+0x1000 and toks[0] == "200": #producer
> write
> IndexError: list index out of range
>
> If i change the except IndexError to except Exception, it will catch it (but
> i believe it's still an IndexError).
> this is python 2.3 on Debian sarge.
>
> any ideas?
Sounds like IndexError has been redefined somewhere, e.g.:
IndexError = 'something entirely different'
foo = []
try:
foo[42]
except IndexError: # will not catch the real IndexError; we're
shadowing it
pass
Try adding "print IndexError" right before your trouble spot, and see
if it outputs "exceptions.IndexError".
--Ben
More information about the Python-list
mailing list