Python for AIPython 3.12 · Pydantic 2.12
Dashboard
0%

try and except

try and except are the statements that catch an error while a program runs, so it can deal with the problem and carry on.

Last updated: 13 Oct, 2026 · Python 3.12

One bad answer stopped the loop in Stand-in model. Catching the error lets the program move on to the next ticket.

Syntax:

python
try:
    ...                  # code that may fail
except SomeError:
    ...                  # runs only if SomeError was raised

Catching a JSON error

Examplefrom the Stand-in model lesson
import json

def ask_model(ticket_text):
    text = ticket_text.lower()
    if "charged" in text or "refund" in text:
        return '{"category": "billing", "priority": 4}'
    if "parcel" in text or "arrived" in text:
        return '{"category": "shipping", "priority": 3}'
    return "I am not sure how to sort this one."

# tickets.json was written back in the JSON lesson
with open("tickets.json") as f:
    tickets = json.load(f)
Example
answer = ask_model("How do I change my password?")

try:
    data = json.loads(answer)
except json.JSONDecodeError:
    data = {"category": "other", "priority": 1}

print(data)

json.JSONDecodeError is the error the traceback in Stand-in model called json.decoder.JSONDecodeError: the same error, with a shorter name. Python runs the try block. If json.loads raises a JSONDecodeError, it jumps to the except block instead of stopping, and the program continues after it.

Name the error you expect. except json.JSONDecodeError handles only unreadable JSON. A typo in a variable name inside the try still stops the program, which is what you want, because a typo is a bug to fix rather than an answer to work around.

Project files used on this pageThis lesson builds on a project from earlier lessons. The code below imports this file. Click a file to see its code, or follow the link to the lesson that wrote it. To run the code yourself, keep it in the same folder.
View the code here
tickets.json
[
  {
    "id": 1,
    "customer": "Asha",
    "text": "I was charged twice for one order"
  },
  {
    "id": 2,
    "customer": "Ben",
    "text": "My parcel has not arrived"
  },
  {
    "id": 3,
    "customer": "Chen",
    "text": "Can I get a refund for the blue mug?"
  },
  {
    "id": 4,
    "customer": "Dara",
    "text": "How do I change my password?"
  },
  {
    "id": 5,
    "customer": "Eli",
    "text": "The parcel arrived but the box was crushed"
  }
]

Keeping the loop going

Example
unsorted = []
for ticket in tickets:
    try:
        # the model sometimes replies in plain english, which json.loads rejects
        data = json.loads(ask_model(ticket["text"]))
    except json.JSONDecodeError:
        unsorted.append(ticket["id"])
        continue
    print(ticket["id"], data["category"])

print("Needs a person:", unsorted)

continue skips the rest of this pass through the loop and moves to the next ticket. All five are handled, and the one the model could not sort is kept for a person instead of being lost.

except SomeError vs a bare except

except json.JSONDecodeError:except:
CatchesOnly unreadable JSONEvery error, typos included
A bug in your codeStill stops the programIs hidden
Use itAlmost alwaysAlmost never

Where try and except show up in AI code

  • Reading a model's answer that may not be the JSON you asked for.
  • Network calls that can fail, retried in Timeouts and retries.
  • Raising a clear error of your own when a value is wrong, the subject of Custom exceptions.
Watch out. A bare except: catches everything, including your own typos, so a broken program looks like it works. Name the error you expect.
Try it yourself
  • Remove continue. There is no error, but ticket 4 now prints billing. Why? (data still holds ticket 3's answer.)
  • Put data = json.loads(answr), with the typo, inside the first try. Does the except catch it?
  • Catch Exception instead of json.JSONDecodeError and confirm a typo'd name inside the try is now hidden.

Little by little, you're building something great.