liveBook · Manning

Exception

As explained in Tiny Python Projects: Learn coding and testing with puzzles and games

An exception is a runtime signal or object representing an abnormal condition that interrupts ordinary program flow and may be handled or propagated.

An exception is a runtime event that interrupts normal execution when Python encounters an invalid operation, missing name, or unexpected input. Reliable programs avoid predictable exceptions or handle them gracefully. section 2.1.6 section 19.3.2

Common Python operations can raise exceptions when their assumptions are violated:

  • Referencing an undefined variable raises NameError. section 2.1.5
  • Unpacking the wrong number of values raises ValueError, as does converting invalid text to integers. section 19.3.2
  • Using a missing dictionary key raises KeyError. section 19.3.2
  • Removing an absent list element raises ValueError; membership checks can prevent it. section 3.3.6

Validate before operating

A CSV-driven workout generator can avoid a sampling exception by checking for usable records and rejecting a requested sample larger than the available data. It exits with a clear error instead of exposing a traceback. section 19.3.4

def main():
    """Make a jazz noise here"""
 
    args = get_args()
    random.seed(args.seed)
    exercises = read_csv(args.file)                               #1
 
    if not exercises:                                             #2
        sys.exit(f'No usable data in --file "{args.file.name}"')
 
    num_exercises = len(exercises)
    if args.num > num_exercises:                                  #3
        sys.exit(f'--num "{args.num}" > exercises "{num_exercises}"')
 
    wod = []                                                       #4
    for name, low, high in random.sample(exercises, k=args.num):
        reps = random.randint(low, high)
        if args.easy:
            reps = int(reps / 2)
        wod.append((name, reps))
 
    print(tabulate(wod, headers=('Exercise', 'Reps')))

Inspect the guarded main() function, which validates parsed input before sampling records. section 19.3.4

How Tiny Python Projects: Learn coding and testing with puzzles and games covers it

How deep it goes
Defines several built-in failures and demonstrates prevention, but does not develop exception-catching syntax or custom exception classes.
Examples
Demonstrates NameError, ValueError, and KeyError through REPL expressions, list removal, malformed CSV fields, and sampling.
What it assumes
Assumes basic Python expressions, variables, lists, dictionaries, functions, and interactive execution.
What you can do after
Diagnose/debug with it by reading tracebacks, identifying violated assumptions, validating inputs, and testing malformed cases.
How it connects
Ties exceptions to variable names, strings, lists, dictionaries, CSV parsing, input validation, and unit testing.

Also explained in

Compare how 25 books explain exception →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Tiny Python Projects: Learn coding and testing with puzzles and games. The section links point to the parts of the book it draws on.