Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Programming · Python · Chapter 09 / 16

Programming learning path

Errors, exceptions & debugging

try/except, custom exceptions, interactive debugging and defensive habits.

try/except: handling errors gracefully

Catch a specific exception type where recovery is possible, instead of letting the whole program crash.

Code that might fail goes inside try:; one or more except SpecificError: blocks catch and handle a named exception type raised inside that block, and code after the entire try/except continues normally if the exception was handled. Catching the narrowest exception type that makes sense (except ValueError: rather than a bare except:) means genuine bugs still surface loudly instead of being silently swallowed alongside the error you actually expected and can recover from, such as bad user input.

Key points

  • try/except catches a specific error type and lets the program continue instead of crashing
  • Catch the narrowest exception type that makes sense, never a bare except:
  • Code after a handled exception continues running normally

Code

Python
editable · browser sandbox
Result
Run the code to see the result.

Catching a specific, expected error type instead of letting the program crash on bad input.

Common pitfalls

  • A bare except: (or except Exception: pass) hides real bugs like typos and TypeErrors indefinitely
  • Wrapping too much code in one try block makes it unclear which line actually raised the exception

Practice exercise

Write a function that reads a number from input(), catching both ValueError (invalid text) and the case of dividing by it if it's zero, with a distinct message for each.

Raising and defining custom exceptions

raise triggers an exception; a custom exception class communicates a specific, domain-meaningful failure.

raise ValueError("message") immediately stops normal execution and propagates the exception up through calling functions until something catches it with a matching except, or the program terminates with a traceback if nothing does. Defining class InsufficientFundsError(Exception): pass and raising that instead of a generic ValueError lets calling code catch and react to that specific domain failure without accidentally also catching unrelated ValueErrors from elsewhere, and it can carry extra data as constructor arguments beyond a plain message string.

Key points

  • raise ExceptionType("message") immediately stops normal execution and propagates up
  • A custom exception class lets callers catch a specific domain failure precisely
  • Custom exceptions can carry structured data, not just a message string

Code

Python
editable · browser sandbox
Result
Run the code to see the result.

A custom exception carrying structured data (requested/available) alongside its message.

Common pitfalls

  • Raising a bare string instead of an exception instance (raise "error") is not valid Python — you must raise an exception object
  • Overusing generic Exception for custom errors instead of a purpose-built subclass makes selective catching impossible

Practice exercise

Define an OutOfStockError exception carrying the product name and requested quantity, and raise it from a purchase(product, quantity, stock) function when stock is insufficient.

Debugging interactively with breakpoint() and pdb

Instead of scattering print() statements, pause execution and inspect live state with the built-in debugger.

Placing breakpoint() at a suspicious line pauses execution there and drops into pdb, an interactive prompt where p variable_name prints a value, n steps to the next line, s steps into a function call, c continues execution, and l lists the surrounding source code — all without editing the source to add and later remove temporary print() calls. Reading a traceback from bottom to top identifies exactly which line and which function raised an exception, which is usually the fastest starting point for figuring out where to place a breakpoint() in the first place.

Key points

  • breakpoint() pauses execution and drops into the interactive pdb debugger
  • p, n, s, c, l are pdb's most-used commands: print, next, step-in, continue, list
  • Read a traceback bottom-to-top to find exactly which line raised the exception

Code

def calculate_discount(price, percent):
    breakpoint()  # execution pauses here
    return price * (1 - percent / 100)

calculate_discount(100, 20)
# at the (Pdb) prompt: p price, p percent, n, c

Pausing execution right before a suspicious calculation to inspect price and percent interactively.

Common pitfalls

  • Leaving a breakpoint() call in committed production code accidentally pauses it whenever that line runs
  • Debugging by adding and removing print() statements repeatedly is slower than one breakpoint() session with pdb commands

Practice exercise

Add a breakpoint() inside a function that computes something incorrectly, use p to inspect the relevant variables at that point, identify the bug, then remove the breakpoint() and fix the code.

Defensive habits: assertions and input validation

assert catches your own programming mistakes early; explicit validation protects against bad external input.

assert condition, "message" raises AssertionError if condition is false, and exists to catch violations of assumptions you control — an internal invariant that should always hold if the code is correct — not to validate external input, because assertions can be globally disabled with the -O interpreter flag, silently removing the check entirely. For anything coming from outside the program's control — user input, a file, a network response — use explicit if/raise validation instead, since that code always runs regardless of interpreter flags and can give the caller a meaningful, specific exception to catch.

Key points

  • assert checks your own internal assumptions, and can be globally disabled with -O
  • Never use assert to validate untrusted external input like user data
  • Explicit if/raise validation always runs and gives a specific, catchable exception

Code

def apply_discount(price, percent):
    assert price >= 0, "internal bug: negative price reached this function"
    if not (0 <= percent <= 100):
        raise ValueError(f"percent must be 0-100, got {percent}")
    return price * (1 - percent / 100)

assert for an internal invariant that should never fail if the code is correct; raise for untrusted external input.

Common pitfalls

  • Using assert user_input > 0 to validate a form field silently disappears when Python runs with -O
  • Assertions with expensive side effects (assert expensive_check()) still run in normal mode, wasting time on every call

Practice exercise

Rewrite a function that uses assert to validate a user-supplied age parameter so it instead raises a proper ValueError, and add an internal assert for a genuinely internal invariant instead.

Source registry

3 chapter references
Errors and Exceptions

try/except/else/finally control flow and exception chaining

Python Software Foundation · Official documentation
Source ↗
The Python Language Reference

Precise scoping, evaluation order and expression semantics

Python Software Foundation · Official reference
Source ↗
The Python Standard Library

Authoritative behavior for built-in types and standard library modules

Python Software Foundation · Official reference
Source ↗