473,399 Members | 3,106 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

Simple exceptions question

Say I have a function foo that throws an IndexError exception, and I
want to handle it:

def foo(a, b, c):
print a[10], b[10], c[10] #, etc.

def main():
#define vars
try:
foo(a, b, c)
except IndexError:
print "Accessed array ", x, " out of bounds!" #???

When the exception is thrown, I don't know what triggered it! a, b,
or c?

I could put a series of if statements in the except clause, but that
defeats the whole purpose of having the exception, right? Is there a
better way?

Thanks in advance!

--Nick
Jul 18 '05 #1
5 1521
Nick Jacobson wrote:
Say I have a function foo that throws an IndexError exception, and
I want to handle it:

def foo(a, b, c):
print a[10], b[10], c[10] #, etc.

def main():
#define vars
try:
foo(a, b, c)
except IndexError:
print "Accessed array ", x, " out of bounds!" #???

When the exception is thrown, I don't know what triggered it! a,
b, or c?
There is IMHO no (at least no obvious) way to find it out. The
"print" is a single statement - an atom from the point of view of
the python interpreter. Its easy to find out, which statement caused
the exception. But its impossible to find out which "part" of one
single statement caused an exception.

And btw what value should "x" have? An object in python has no name.
I could put a series of if statements in the except clause, but
that
defeats the whole purpose of having the exception, right? Is there
a better way?


Yes: create your own list class (maybe by inheriting list). Give each
instance an unique name. Use a setitem method like this:

class seq(list):
# some code suppressed...
def __getitem__(self,index):
try: list.__getitem__(self,index)
except IndexError,e:
e.index = index
e.name = self.name
raise e

Thus you can write the except clause as:

except IndexError, e:
print "Accessed*array*", e.name, "*out*of*bounds at", e.index

Mathias
Jul 18 '05 #2
Nick Jacobson wrote:
Say I have a function foo that throws an IndexError exception, and I
want to handle it:

def foo(a, b, c):
print a[10], b[10], c[10] #, etc.

def main():
#define vars
try:
foo(a, b, c)
except IndexError:
print "Accessed array ", x, " out of bounds!" #???

When the exception is thrown, I don't know what triggered it! a, b,
or c?

I could put a series of if statements in the except clause, but that
defeats the whole purpose of having the exception, right? Is there a
Not necessarily. If you expect the IndexError to be rare you could easily
afford the extra time to detect the source of the error.
better way?


The problems I see with your approach:

You are interested in the details of a failure that happens in another
function. That breaks the abstraction and I'd rather invent a custom
Exception.

You wrap multiple points of failure into one try block when you are
interested in the exact source of failure.

foo() can "semi-fail", i. e. start printing something and then choke.

Here is how I would do it:

class FooError(Exception): pass

def foo(a, b, c):
try:
a = a[10]
except IndexError:
raise FooError("a out of bounds")

try:
b = b[10]
except IndexError:
raise FooError("b out of bounds")

try:
c = c[10]
except IndexError:
raise FooError("c out of bounds")

print a, b, c
def main():
try:
foo(*map(range, [11, 11, 5]))
except FooError, e:
print "Problem in foo():", e

main()
Peter

Jul 18 '05 #3
Thanks for the reply! I'm definitely trying this out..
the python interpreter. Its easy to find out, which statement caused
the exception.
How can you do that?
Yes: create your own list class (maybe by inheriting list). Give each
instance an unique name. Use a setitem method like this:

class seq(list):
# some code suppressed...
def getitem (self,index):
try: list. getitem (self,index)
except IndexError,e:
e.index = index
e.name = self.name
raise e

Thus you can write the except clause as:

except IndexError, e:
print "Accessed array ", e.name, " out of bounds at", e.index

Mathias


It says that "self.name" is undefined:
"AttributeError: 'seq' object has no attribute 'name'"
Jul 18 '05 #4
Not sure if this is all you need, but have tried this?

def main():
#define vars
try:
foo(a, b, c)
except IndexError:
traceback.print_exc()
Jul 18 '05 #5
Not sure if this is all you need, but have tried this?

def main():
#define vars
try:
foo(a, b, c)
except IndexError:
import traceback
traceback.print_exc()
Jul 18 '05 #6

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

Similar topics

4
by: Steve | last post by:
I have read a couple articles online, read my Jesse Liberty book but I am still confused as to just what the best practices are for using exceptions. I keep changing how I'm working with them and...
30
by: galiorenye | last post by:
Hi, Given this code: A** ppA = new A*; A *pA = NULL; for(int i = 0; i < 10; ++i) { pA = ppA; //do something with pA
5
by: adam.timberlake | last post by:
I've just finished reading the article below which goes into some depth about exceptions. The article was rather lucid and so I understand how to implement it all, the thing I'm having trouble with...
22
by: ben mitch | last post by:
Hi I hope you'll see this cross-post (c/c++) as appropriate. I also admit immediately that the question *may* turn out to be compiler-/os-specific, in which case I apologize. But I wonder if...
23
by: ben mitch | last post by:
Hi I hope you'll see this cross-post (c/c++) as appropriate. I also admit immediately that the question *may* turn out to be compiler-/os-specific, in which case I apologize. But I wonder if...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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...
0
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,...

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.