9.1 Exceptions and Handling
An exception is an abnormal situation that occurs while a program is running. An exception does not always mean the program must crash; with proper handling, a program can show a message, record the problem, or continue with later logic.
Common Exceptions
Common exceptions include:
ValueError: a value is invalid, such as converting"3.6"toint.ZeroDivisionError: division by zero.IndexError: list index out of range.KeyError: a dictionary key does not exist.FileNotFoundError: opening a missing file.AttributeError: accessing a missing attribute.
if, it often should be. Exceptions are best for failures that may only become clear at runtime.try, except, else, and finally
Put risky code in try, error handling in except, success-only code in else, and cleanup code in finally. The finally block runs whether an exception happens or not.
try:
dividend = int(input("Enter dividend: "))
divisor = int(input("Enter divisor: "))
quotient = dividend / divisor
except ValueError:
print("Only integers are supported.")
except ZeroDivisionError:
print("Divisor cannot be 0.")
else:
print("%d / %d = %.2f" % (dividend, divisor, quotient))
finally:
print("This calculation is finished.")One possible run:
Enter dividend: 21
Enter divisor: 4
21 / 4 = 5.25
This calculation is finished.else separates success-only work from the risky code inside try. The flow becomes clearer: try attempts, except handles failure, else handles success, and finally cleans up.
Catch Specific Exceptions
Do not start by writing an overly broad except Exception. If every exception is caught, real bugs may be swallowed and become harder to find.
try:
score = int(input("Enter score: "))
except ValueError:
print("Score must be an integer.")This code catches only ValueError because the expected failure is “input cannot be converted to an integer.”
raise
raise actively throws an exception. It is useful for saying “this input does not satisfy the function's requirements.” The problem is detected in the right place, and caller code decides how to handle it.
def normalize_score(score):
if score < 0 or score > 100:
raise ValueError("Score must be between 0 and 100.")
return score / 100
try:
score = int(input("Enter score: "))
ratio = normalize_score(score)
except ValueError as error:
print("Invalid input: %s" % error)
else:
print("Score ratio: %.2f" % ratio)One possible run:
Enter score: 120
Invalid input: Score must be between 0 and 100.Here, normalize_score() does not print the user message. It only protects its own input rule. The outer caller decides how to explain the problem to the user.