liveBook · Manning

Exception

As explained in Python Workout, Second Edition

An exception is a Python runtime event representing an abnormal condition that can interrupt normal execution and be handled by exception-handling constructs.

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

How Python Workout, Second Edition covers it

How deep it goes
Demonstrates try/except conversion, retry control flow, and custom exception classes, but does not develop broader exception hierarchies.
Examples
Uses integer conversion, rainfall input loops, and tax calculation with separate low-hour and high-hour exceptions.
What it assumes
Assumes basic Python functions, loops, input conversion, and comprehensions while emphasizing exception handling through executable problems.
What you can do after
Apply try/except to validate conversions, retry interactive input, and raise meaningful errors from reusable functions.
How it connects
Connects try/except, ValueError, input validation, list comprehensions, generator expressions, and custom exception classes.

Also explained in

Compare how 25 books explain exception →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.