androidengineers.Book a session

Python 06 · Errors and resource management

Exceptions, traceback reading, and error boundaries

articleSelf-paced

Learn the concept

Exceptions interrupt normal control flow. A traceback shows the chain of calls leading to the error. Start with the exception type and the most relevant line in your code, then inspect the values that caused it.

Catch errors where you can do something useful: recover, add context, or convert them to a documented application result. Catching Exception around an entire program and returning success conceals defects. Use specific exception types when possible and preserve the original cause when translating an error.

A finally block runs during normal completion and exception unwinding and is useful for cleanup. Do not return from finally because it can suppress an earlier exception. Validation failures should remain distinguishable from unexpected programming bugs.

Run and inspect

def parse_count(text):
    try:
        value = int(text)
    except (TypeError, ValueError) as error:
        raise ValueError("Count must be whole-number text") from error
    if value < 0:
        raise ValueError("Count must be nonnegative")
    return value

assert parse_count("12") == 12

Your exercise

Call the parser with valid text, invalid text, None, and a negative value. Inspect the traceback chain for conversion errors.

Check your understanding

You preserve the distinction between conversion failure and an out-of-range value, and the successful case returns an integer.

YOUR LEARNING JOURNEY

0 of 119 available lessons completed

Progress saved in this browser. No account needed.
Exceptions, traceback reading, and error boundaries | Forward Deployed Engineer | Android Engineers