Try... except....Try again?

Lie Ryan lie.1296 at gmail.com
Fri Jul 17 17:58:21 EDT 2009


Xavier Ho wrote:
> oops, wrong address.
> 
> When will reply-to tag appear on the Python mailing list? =/
> 
> Good idea, Steven and MRAB.
> 
> I changed my code to the following:
> 
> 
>     def nPrime(self, n):
>         "Returns nth prime number, the first one being 2, where n = 0.
> When n = 1, it returns 3."
>         for x in range(n+2):
> 
>             try:
>                 return self.primes[n]
>             except IndexError:
>                 self.next()

If you're looking for speed, you should be aware that a failed
try-clause is quite expensive in python and often (as in this case)
codes using exception can be less readable than the one without since a
program's flow in the case of exception is not linear (the non-linear
execution is useful for quickly breaking out from nests of clauses, but
not necessary in this case).

Semantically, it is also wrong. Not finding the n'th prime in the cache
is not really an exceptional case.

If you insists on using a try-except clause, use it this way:

# untested
def nPrime(self, n):
    try:
        return self.primes[n]
    except IndexError:
        for _ in xrange(len(self.primes), n+1):
            self.next()
        return self.primes[n]




More information about the Python-list mailing list