Exceptions aren't exceptional

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:

def divide_with_exception(number, divisor):
    try:
        print("{} / {} = {}".format(
            number, divisor, number / divisor * 1.0))
    except ZeroDivisionError:
        print("You can't divide by zero")

def divide_with_if(number, divisor):
    if divisor == 0:
        print("You can't divide by zero")
    else:
        print("{} / {} = {}".format(
            number, divisor, number / divisor * 1.0))

These two functions behave identically. If divisor is zero, an error message is printed, otherwise, a message printing the result of division is displayed. ...

Get Python 3 Object Oriented Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.