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. Clearly, we could avoid a ZeroDivisionError
ever being thrown by testing for it with an if
statement. Similarly, we can avoid an IndexError
by explicitly checking whether...