Search⌘ K
AI Features

Exceptions Aren’t Exceptional

Explore how to use exceptions in Python not just for errors but as a flow control mechanism. Learn the EAFP approach, see practical examples with inventory management, and understand why exceptions can simplify program logic and improve code maintainability.

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:

Python 3.10.4
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 ...