if or exception

Steve dippyd at yahoo.com.au
Fri Jul 30 00:10:46 EDT 2004


Duncan Booth wrote:

> However, it seems to me that I would be unlikely to use either of these. I 
> can't think of a situation where I would want a value that is either the 
> result of a division, or 0 if the division failed.

What about code for cos(x)/x? By l'Hôpital's Rule, the 
limit as x->0 is 0.

Admittedly practical applications for cos(x)/x aren't 
as common as for sin(x)/x. Perhaps evaluating the 
derivative of sinc(x) is a better example.

Or one might want code to handle a continued fraction 
of the form [1; 2, 1, 0] which should evaluate as 1.5 
except for the pesky divide-by-zero error.

The moral of the story: even if you can't think of an 
application for something, somebody else might.

 > It is much more likely
> that you want to execute some different code if the list is empty than that 
> you want a different value.

But the question still remains: is it better to do this:

if myList:
     call_standard_code(myList)
else:
     call_exceptional_code(myList)

or this:

try:
     call_standard_code(myList)
except SomeSortOfExceptionHere:
     call_exceptional_code(myList)


The essential question remains: is it better to test 
for exceptional cases first or just try it and catch 
the exception when it happens?

And the answer is, "It depends."

Apart from issues of aesthetics, it also depends on how 
often you expect exceptions to occur, and how much work 
is needed to determine whether an error will occur 
before hand. If it is easy to check for errors up 
front, I'd probably stick with the if form. If it takes 
just as much work to determine the existance of the 
error condition as it takes to actually perform your 
calculation, stick to using the try...except form.

But the only way to know for sure which is quicker is 
to write both versions and time them with realistic data.



-- 
Steven




More information about the Python-list mailing list