Programs meet conditions they cannot always predict: unreliable systems, misleading input, and mistakes in code. In Python, an exception signals an unexpected event during execution. It need not mean the program has a bug; what matters is whether the application can respond usefully. section 5.0 section 5.1
A division that cannot finish
Dividing by zero raises ZeroDivisionError. Python stops normal execution and searches back through the call stack for a handler. If it finds none, the program exits and prints a stack trace showing the calls and line where the exception arose. Invalid numeric input can similarly raise ValueError. section 5.1
Catch an exception where the code has enough context to do something useful. A function might retry or correct a condition locally. Otherwise, let the exception travel upward: a caller may know which alternative to take or what to tell the user. Log an unhandled failure and its stack trace when that information is needed for debugging. section 5.2.1 section 5.2.2
def range_check_user_input(value):
if not 0 < value <= 100:
raise ValueError("value range exceeded", value)
# additional functionality
A range check raises ValueError when an input falls outside 0 < value ≤ 100, leaving the decision about what to do next to its caller. section 5.3
def get_data_from_user():
# initialization and gather user input
try:
range_check_user_input(value)
except ValueError as e:
print(e)
# restart code to get user input
The caller catches that ValueError with try/except, shows the problem to the user, and can request input again. section 5.3
Exceptions are one part of a function’s API output alongside return values and actions on the system. Raise one to signal a condition the function cannot usefully resolve; handle it at the level that can choose a sensible response. section 3.1.3 section 5.3
























