473,591 Members | 2,842 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

except clause not catching IndexError

I'm sorry if this is a FAQ or on an easily-accesible "RTFM" style page, but
i couldnt find it.

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?

thanks,
-derek
Feb 22 '06 #1
7 6381
Derek Schuff <ds*****@purdue .edu> writes:
I have some code like this:
[...]
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


Did you by any chance do something like:

except ValueError, IndexError:

at some point earlier in this function? That, when catching ValueError
assigns the resulting exception to IndexError (and so the following
except IndexError: wouldn't work as IndexError is no longer what you
think it is). The correct syntax for catching multiple exceptions is:

except (ValueError, IndexError), targetVariable:

You could verify this by doing a print repr(IndexError ) before your
line 202, to see that it really is the IndexError builtin.

--
=============== =============== =============== =============== ===
<er**********@a ndreasen.org> London, E14
<URL:http://www.andreasen.o rg/> <*>
=============== =============== =============== =============== ===

Feb 22 '06 #2
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.Ind exError".

--Ben

Feb 22 '06 #3
Derek Schuff wrote:
I have some code like this: <code nobody else can run>
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
This was good, the actual error; I suspect you overwrote IndexError.
The general principal is to boil down your code to the smallest code
that exhibits the problem. This is not just to aid us, since usually
at some point you delete a block of lines and the problem goes
magically away.
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. More points for identifying Python version and OS.
any ideas?

As above, but to test my theory:

....
except Exception, e:
print 'caught %r: %r (IndexError is %r)' % (
e, e.__class__, IndexError)

--Scott David Daniels
sc***********@a cm.org
Feb 22 '06 #4
Erwin S. Andreasen wrote:
Did you by any chance do something like:

except ValueError, IndexError:

at some point earlier in this function? That, when catching ValueError
assigns the resulting exception to IndexError (and so the following
except IndexError: wouldn't work as IndexError is no longer what you
think it is). The correct syntax for catching multiple exceptions is:

except (ValueError, IndexError), targetVariable:

You could verify this by doing a print repr(IndexError ) before your
line 202, to see that it really is the IndexError builtin.


hey, nice catch. In fact I did exactly that. in my search for a solution for
this problem i discovered the catch-a-tuple-of-exceptions error, and in
fact fixed it, but didn't realize that it was related to the one I posted.
(the idea that exceptions can be redefined caught me off guard).

thanks (to both of you who responded),
-derek
Feb 22 '06 #5
Erwin S. Andreasen wrote:
Did you by any chance do something like:

except ValueError, IndexError:

at some point earlier in this function? That, when catching ValueError
assigns the resulting exception to IndexError (and so the following
except IndexError: wouldn't work as IndexError is no longer what you
think it is). The correct syntax for catching multiple exceptions is:

except (ValueError, IndexError), targetVariable:

You mean to say that "except X,Y:" gives different
results to "except (X,Y):"?

That can't be good.
try: .... L = []; print L[2]
.... except ValueError, IndexError:
.... print "Error!"
....
Traceback (most recent call last):
File "<stdin>", line 3, in ?
IndexError: list index out of range
try:

.... L = []; print L[2]
.... except (ValueError, IndexError):
.... print "Error!"
....
Error!
And here I was thinking that commas make tuples, not
brackets. What is happening here?
--
Steven.

Feb 23 '06 #6
Steven D'Aprano <st***@REMOVEME cyber.com.au> wrote:
And here I was thinking that commas make tuples, not
brackets. What is happening here?


What is happening is that the syntax for forming tuples is one of Python's
warts. Sometimes the comma is what makes a tuple:
a = 1, 2
type (a) <type 'tuple'>

Sometimes, it is the parens:
b = ()
type (b)

<type 'tuple'>

Sometimes the syntax is ambiguous and you need both. This happens anytime
you have a list of comma separated things, such as in the arguments to a
function:

a = foo (1, 2) # two integer arguments
b = foo ((a, 2)) # one tuple argument

The except clause of a try statement is one of those times.
Feb 23 '06 #7
Steven D'Aprano <st***@REMOVEME cyber.com.au> wrote:
You mean to say that "except X,Y:" gives different
results to "except (X,Y):"?
[ ... ]
And here I was thinking that commas make tuples, not
brackets. What is happening here?


Similar kind of thing to what's happening here:
print "Hello,", "world!" Hello, world! print ("Hello", "world!")

('Hello', 'world!')

And for that matter foo(a, b) v. foo((a, b)). Commas make
tuples, but they're also argument separators, and if you're
using a tuple as an argument you need the brackets to
indicate precedence.

--
\S -- si***@chiark.gr eenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
Feb 23 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

39
6033
by: Erlend Fuglum | last post by:
Hi everyone, I'm having some trouble sorting lists. I suspect this might have something to do with locale settings and/or character encoding/unicode. Consider the following example, text containing norwegian special characters æ, ø and å. >>> liste =
0
1537
by: John J. Lee | last post by:
Bare "except:", with no exception specified, is nasty because it can easily hide bugs. There is a case where it seemed useful to me in the past. Now it seems like a bad idea to me (but I think I might still be confused about it, hence this post). It's this: When you're processing a input from a file-like object connected to an external source like a network connection, disk file etc, you have to expect broken, and often malicious,...
20
3904
by: John Salerno | last post by:
I'm starting out with this: try: if int(text) 0: return True else: self.error_message() return False except ValueError: self.error_message()
35
1995
by: Arnaud Delobelle | last post by:
Hi all, Imagine I have three functions a(x), b(x), c(x) that each return something or raise an exception. Imagine I want to define a function that returns a(x) if possible, otherwise b(x), otherwise c(x), otherwise raise CantDoIt. Here are three ways I can think of doing it: ----------
2
1396
by: AWasilenko | last post by:
I can't figure out this problem Im having, I just can't understand why it is ignoring the call I put in. First the code (This is a cherrypy website): import sys, cherrypy, html class Root: @cherrypy.expose def index(self, pageid = "Index"): selection = html.Page()
5
1788
by: Nebur | last post by:
I'm using the contract.py library, running Python 2.4.4. Now I'm confronted with the following exception backtrace: (...) File "/usr/lib/python2.4/site-packages/contract.py", line 1265, in _check_preconditions p = f.__assert_pre AttributeError: 'function' object has no attribute '__assert_pre' For my surprise, I found that the code of contract.py around line 1265
9
5147
by: ssecorp | last post by:
Is this correct use of exceptions? to raise an indexerror and add my own string insetad of just letting it raise a IndexError by itself and "blaming" it on list.pop? class Stack(object): def __init__(self, *items): self.stack = list(items) def push(self, item): self.stack.append(item)
11
2661
by: cnb | last post by:
If I get zero division error it is obv a poor solution to do try and except since it can be solved with an if-clause. However if a program runs out of memory I should just let it crash right? Because if not then I'd have to write exceptions everywhere to prevent that right? So when would I actually use try-except? If there can be several exceptions and I just want to catch 1 or 2?
9
3997
by: ssecorp | last post by:
or why does this take so god damn long time? and if I run into an IndexError it break out of the inner loop right? so having range up to 10000000 or 1000 wouldn't matter if biggest working x is 800? def getPixels(fileName): im = PIL.Image.open(fileName) colors = for y in range(1, 1000): row =
0
8236
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8362
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
7992
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6639
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5732
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3891
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2378
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1465
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1199
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.