-2

Where should I put the Exception handling? which one is the best solution for the code:

def spam(divideBy):
    try:
        return 42 / divideBy
    except ZeroDivisionError:
        print('Error: Invalid argument.')
print(spam(2))
print(spam(12))
print(spam(0))
print(spam(1))

OR

def spam(divideBy):
    return 42 / divideBy

try:
    print(spam(2))
    print(spam(12))
    print(spam(0))
    print(spam(1))

except ZeroDivisionError:
    print('Error: Invalid argument.')
Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
sf31
  • 45
  • 3
  • 10
  • 1
    Handle whichever exceptions can be handled completely in the context of the function using the first method. The rest of the exceptions should be thrown to the caller using method 2. Depends on context. – rdas Oct 01 '19 at 08:32
  • 1
    I like more your first code, but following your codestyle, I will return"Error: Invalid argument") instead print, cause you invoce function inside print(spam(1)) – Wonka Oct 01 '19 at 08:36
  • What do you mean? I followed the indentation rule – sf31 Oct 01 '19 at 08:39

1 Answers1

1

The first method means that any user of the spam() function needs to check whether it returns a number or None before they try to use the result (unless all they're doing is printing the result, as in your example).

The second method means all users have to add try/except around the calls.

Either way, the caller has to do something to deal with the zero division error.

The second method is more flexible, since the callers can customize the way they deal with the exception. The first method always prints the same message and returns None, the caller can't do anything about it.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • but as you may notice in the second method, the last number is won't be printed. What If I want to print the last number as well? – sf31 Oct 01 '19 at 08:44
  • 1
    You can put a separate `try/except` around each call, instead of wrapping them all. – Barmar Oct 01 '19 at 08:45