BeginnerCoder

Lesson 21 — Error handling and retries

When things go wrong

Two things fail all the time in agents:

  1. The model returns bad output — prose instead of JSON. Fix: catch the error, add a message like "Reply with valid JSON only", and retry (ask again), up to a limit.
  2. A tool raises an exception — dividing by zero, a missing file, a site that is down. Fix: catch it and turn it into an observation, such as "error: ZeroDivisionError: division by zero". The model reads the error and can try something else.
try:
    return risky()
except Exception as err:
    return "failed: " + str(err)

type(e).__name__ is the error's class name; str(e) is its message.

Why it matters: a crash ends the whole run. An error the model can see is just one more step.

Want it another way?
Task

Run it first: it crashes with ZeroDivisionError. Make safe_call catch any exception and return "error: <ErrorName>: <message>".

Run your code — when the output matches the task, you will see a green check. Then mark the lesson complete.

← Back
Next →
Test your knowledge

A quick 3-question quiz on this lesson — instant feedback.

Enjoying this lesson? Share it.

Keep going with AI Agents Foundations

Ready for more? Optional paid resources that pick up where this lesson leaves off.

Some links on this page are affiliate links: we may earn a commission at no extra cost to you. As an Amazon Associate I earn from qualifying purchases.