July 2010
Beginner to intermediate
404 pages
10h 6m
English
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. ...
Read now
Unlock full access