Try/except vs. if/else

Tim Rowe tim at remove_if_not_spam.digitig.co.uk
Tue Sep 23 14:47:10 EDT 2003


On Tue, 23 Sep 2003 11:10:49 -0400, Shu-Hsien Sheu <sheu at bu.edu>
wrote:

>Hi,
>
>In my understanding, using try/except rather than if/else is more 
>pythonic. 

Rule of thumb: when the block of code is still doing what it's
supposed to do, use if/else. If it's failing to do what it's supposed
to do, use try/except. "except" should be an /exception/!

>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

I'd reckon that to be a bad use of try/except; the "exception" is a
perfectly normal case.

>case 2: if/else
>
>hit = 0
>for i in my_test:
>    if 'some' in i:
>       hit = 1

My /guess/ is that this would be faster than case 1, as well as
clearer!

>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.

Yes.  The first is clear and concise, the second is verbose and
unclear!  Also the second could mask a genuine ValueError if a, b, or
c is an evaluation rather than a simple variable, so you'd think that
neither a nor c was in b when in fact you have no idea: something went
invisibly wrong and you never actually completed the search.

So try/except /only/ when something has gone wrong and you need to go
into some sort of recovery or termination, /not/ for routine tests.




More information about the Python-list mailing list