An exception is a Python runtime event that interrupts normal execution when an operation fails or input violates an expected condition. Handle expected failures with try and except instead of relying on preliminary checks that do not match the operation precisely. section 8.7 section 5.9
Use exceptions to make input and reusable functions behave predictably:
- Attempt the operation optimistically inside try, such as converting a string with int. section 8.7
- Catch the expected exception, such as ValueError, and report the problem or repeat the input loop. section 5.9
- Raise a purpose-specific exception when a function receives invalid values, especially in reusable modules. section 9.3
- Prefer operation-based validation over str.isdigit when accepted values include negative integers. section 8.7
Converting user input
try: n = int(s) print(f'You entered {n}. 2*{n} = {2*n}.') except ValueError: print(f'{s} is not numeric.') This accepts both positive and negative integers; trapping the exception inside a list comprehension would require moving the logic into a function. section 8.7
class HourTooLowError(Exception): pass
class HourTooHighError(Exception): pass
def calculate_tax(amount, state, hour):
if hour < 0:
raise HourTooLowError(f'Hour of {hour} is < 0')
if hour >= 24:
raise HourTooHighError(f'Hour of {hour} is >= 24')
return amount + (amount * rates[state] * time_percentage(hour))
Inspect a reusable function that defines and raises separate exceptions for hours below zero and hours at least twenty-four. section 9.3
























