Try/except vs. if/else

Hung Jung Lu hungjunglu at
Sat Sep 27 11:01:19 CEST 2003

Shu-Hsien Sheu <sheu at> wrote in message news:<mailman.1064330017.10730.python-list at>...
> catching multiple errorrs. However, problems occur if the criteria is 
> composed of "or" rather than "and". For instance:
> if (a in b) or (c in b):
>     *do something
> try:
>     b.index(a)
>     b.index(c)
>     *do something
> except ValueError:
>    pass

For the "or" case, actually the exception trick works rather well.
Usually people raise events by hand:

class Found(Exception): pass

    if a in b: raise Found
    if c in b: raise Found
except Found:
    do something

Of course, one can supply additional information, as in:

    if a in b: raise Found('a in b')
    if c in b: raise Found('c in b')
except Found, e:
    print str(e)

Hung Jung

More information about the Python-list mailing list