BeginnerCoder

Lesson 18 — Errors: try / except

Handle failures

When something goes wrong, Python raises an error and the program stops. try/except lets you catch it: risky code goes under try, and the except branch runs only if that error happens. Name the error type after except, so unexpected errors still show up.

try:
    n = int("abc")
except ValueError:
    n = 0

Why it matters: bad input and missing files are normal — a good program answers with a clear message instead of crashing.

Want it another way?
Task

Finish the except branch so that dividing by zero returns "cannot divide by zero".

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 Python 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.