Simple exceptions question

Peter Otten __peter__ at web.de
Mon Aug 16 16:40:43 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?
> 
> 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




More information about the Python-list mailing list