Python - Try...Except

Overview

Estimated time: 20–30 minutes

Handle errors gracefully with try/except/else/finally. Learn when to catch, when to let exceptions propagate, and how to raise your own.

Learning Objectives

  • Use try/except/else/finally properly.
  • Create and raise custom exceptions.
  • Apply EAFP vs LBYL and avoid broad excepts.

Prerequisites

Basic structure

try:
    x = int(input("Enter an integer: "))
except ValueError as e:
    print("Not an integer", e)
else:
    print("You entered", x)
finally:
    print("always runs")

Raising and chaining

def parse_age(s: str) -> int:
    try:
        return int(s)
    except ValueError as e:
        raise ValueError(f"invalid age: {s}") from e

Custom exceptions

class ConfigError(Exception):
    pass

raise ConfigError("missing DB_URL")

Common Pitfalls

  • Using bare except:; catch specific exceptions instead.
  • Swallowing exceptions without logging or re-raising; this hides bugs.

Checks for Understanding

  1. When does the else block run?
  2. How do you preserve the original traceback when raising a new error?
Show answers
  1. When no exception was raised in the try block.
  2. Use raise ... from e to chain exceptions.

Exercises

  1. Wrap file opening and parsing in a try/except with a helpful error message.
  2. Create a custom exception type for invalid configuration and raise it when an env var is missing.