Intermediate·20 min·0/47 done

Python Try Except

Handle errors with try and except. Catch specific problems and fail clearly on the rest.

Why it matters: LLM APIs time out, rate-limit, and return bad JSON. Catch what you can retry, and do not hide real bugs.

Basics

Reading Errors

Read a traceback from the bottom up. The last line names the error.

Common types:

  • KeyError - missing dict key
  • ValueError - right type, bad value
  • TypeError - wrong type
  • FileNotFoundError - path not found
  • ZeroDivisionError - divide by zero

Tiny example

Catch a missing key and print a message.

payload = {"model": "mini"}
try:
    print(payload["temperature"])
except KeyError as err:
    print("missing:", err)

Basics

try / except / finally

Put risky code in try. Handle known problems in except.

Catch specific exceptions. A bare except: hides bugs and can catch Ctrl+C.

else runs when no error happened. finally always runs. Common mistake: except Exception: around everything.

Tiny example

Fall back when a float parse fails.

raw = "hot"
try:
    temperature = float(raw)
except ValueError:
    temperature = 0.2
print(temperature)

Basics

Raise and Retry

Use raise to signal a problem. raise ... from err keeps the original cause.

Retry timeouts and rate limits. Do not retry bad auth or bad input.

A simple pattern: try, catch the transient error, wait 2 ** attempt, try again.

Tiny example

Show backoff wait times for each attempt.

for attempt in range(4):
    wait = 2 ** attempt
    print(attempt, "wait", wait)

Then AI / ML

AI / ML examples

Same idea, used in real AI work. Press Try in lab to run it.

AI / ML example

AI / ML: safe config parse

Missing or bad temperature falls back to a default.

In AI / ML: LLM configs often miss keys or send temperature as a string.

example.py

Python

payload = {"model": "gpt-4.1-mini"}
try:
    temperature = float(payload["temperature"])
except KeyError:
    temperature = 0.2
except (TypeError, ValueError):
    temperature = 0.2
print("temperature =", temperature)

AI / ML example 2

AI / ML: retry a flaky call

Simulate a timeout, then succeed on a later attempt.

In AI / ML: LLM gateways hit rate limits and timeouts in production.

example.py

Python

attempts = {"count": 0}

def flaky_call():
    attempts["count"] += 1
    if attempts["count"] < 3:
        raise TimeoutError("timeout")
    return {"answer": "ok"}

for attempt in range(5):
    try:
        print(flaky_call())
        break
    except TimeoutError:
        print("retry", attempt + 1)

Takeaways

  • 1Read tracebacks from the bottom up.
  • 2Catch specific exceptions, not bare except.
  • 3Retry transient failures; fail fast on bad input.
Certificate