Try/except vs. if/else

Hung Jung Lu hungjunglu at yahoo.com
Sat Sep 27 05:01:19 EDT 2003


Shu-Hsien Sheu <sheu at bu.edu> wrote in message news:<mailman.1064330017.10730.python-list at python.org>...
> 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

try:
    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:

try:
    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