Exceptions Aren’t Exceptional

Learn why exceptions aren’t exceptional and when it is better to use them.

Novice programmers tend to think of exceptions as only useful for exceptional circumstances. However, the definition of exceptional circumstances can be vague and subject to interpretation. Consider the following two functions:

Press + to interact
def divide_with_exception(dividend: int, divisor: int) -> None:
try:
print(f"{dividend / divisor=}")
except ZeroDivisionError:
print("You can't divide by zero")
def divide_with_if(dividend: int, divisor: int) -> None:
if divisor == 0:
print("You can't divide by zero")
else:
print(f"{dividend / divisor=}")

These two functions behave identically. If divisor is zero, an error message is printed; otherwise, a message printing the result of the division is displayed. We could avoid ZeroDivisionError ever being thrown by testing for it with an if statement. In this example, the test for a valid division is relatively simple-looking (divisor == 0). In some cases, it can be rather complex. In some cases, it may involve computing intermediate results. In the worst cases, the test for will this work? involves using a number of other methods of a class, too – in effect – dry-run the operation to see if there would be an error along the way.

When do we use exceptions?

Python programmers tend to follow a model summarized by “It’s Easier to Ask Forgiveness Than Permission,” sometimes abbreviated EAFP. The point is to execute code and then deal with anything that ...