1

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?

Jonas
  • 121,568
  • 97
  • 310
  • 388
Adam Hunyadi
  • 1,890
  • 16
  • 32
  • 2
    [EAFP](https://docs.python.org/3/glossary.html#term-eafp) is a mentality that is used in lots of well-written python code :-) – mgilson Jun 03 '16 at 21:41
  • 1
    @jonrsharpe -- I agree that this question looks like a dupe of the one you referenced, but frankly, when I try to read the question you referenced, I don't even know what they're asking unless I disregard the body of the question and only read the title... – mgilson Jun 03 '16 at 21:45

0 Answers0