I'm not too familiar with the practices in python and I would like to know if it's a good practice to use (abuse) exceptions when they perform exactly the check I need, or should they only be used to check illegal arguments (eg. do they have performance penalty).
Example (a number is an amicable number if it has a pair, and the sum of its real divisors is its pair and vice-versa. This code prints out the number):
amicable_numbers = []
for a, b in divisor_sums:
try:
pair = divisor_sums[b][1]
except IndexError:
pair = get_divisor_sum(prime_numbers, a)
if a == pair and b != a:
print a, pair
This is the equivalent code with if-else checks:
amicable_numbers = []
max_calculated = len(divisor_sums)
for a, b in divisor_sums:
if b < max_calculated:
pair = divisor_sums[b][1]
else:
pair = get_divisor_sum(prime_numbers, a)
if a == pair and b != a:
print a, pair
I tried benchmarking the runs, but didn't notice much of a performance difference, the if-else was ever so slighlty faster (~1-2% speed improvement in this case), but the first code is much more readable for me. So my question is: do I have to avoid abusing the exceptions? Is there a rule when it is appropriate to use them?