Try/except vs. if/else

Shu-Hsien Sheu sheu at bu.edu
Tue Sep 23 11:10:49 EDT 2003


Hi,

In my understanding, using try/except rather than if/else is more 
pythonic. However, sometimes it is difficult to use the later.
For example, I want to search for a sub string in a list composed of 
strings. It is considered "possitive" if there is a match, no matter how 
many.

my_test = ['something', 'others', 'still others']

case 1: try/except

hit = 0
for i in my_test:
    try:
       i.index('some')
       hit = 1
    except ValueError:
       pass



case 2: if/else

hit = 0
for i in my_test:
    if 'some' in i:
       hit = 1


It seems to me that in a simple searching/matching, using if might be 
better and the code is smaller. Try/except would have its strengh on 
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

The above two are very  different.

Am I right here?

-shuhsien






More information about the Python-list mailing list