Simple exceptions question

Mathias Waack M.Waack at gmx.de
Mon Aug 16 16:13:37 EDT 2004


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



More information about the Python-list mailing list