Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Python
  • Python for AI: The Five Tools You Actually Need
  • Thinking Like a Python Architect in an AI-First World
  • Your First Python Program: print, Comments, sep and end
  • Set Up PyCharm for Python: Install, First Project and First Run
  • Run a Python File and Read the Error: Tracebacks in Three Steps
  • Python Data Types, Variables and Strings: Indexing, Slicing and f-strings
  • Python Operators: Arithmetic, Comparison, Logical, Membership, Identity and Precedence
  • Python Conditionals and Loops: if/elif/else, for, while, break and continue
  • Looping Over Real Data in Python: Dicts, Lists of Dicts, enumerate and zip
  • Checking AI-Written Python Code: A Six-Step Habit That Finds Three Hidden Faults
  • Python Basics Practice: Report Card, Shopping Cart and Password Checker from a Prompt
  • Python Functions: Parameters, Return, Scope (LEGB), *args and **kwargs
  • Type Hints on Python Functions: Parameters, Returns, None and Collections
  • Python lambda, map, filter, Modules and Packages (with pip and venv)
  • Python Functions Practice: Bonus Calculator, Product Pipeline and a Math Package
  • Python Lists, Tuples, Sets and Dicts, Plus Type Hints on Variables
  • Python Comprehensions: List, Dict, Set and Generator Expressions, Read as Loops
  • Python Class Methods, Static Methods and Properties: What Each One Receives
  • Python Classes and Objects: __init__, self and PEP 8 Names
  • Python Inheritance and Polymorphism: super(), Overriding and Duck Typing
  • Python Multiple Inheritance, the MRO and Mixins
  • Python Encapsulation and Special Methods: Underscores, __str__, __add__ and __len__
  • Python Composition, Abstract Classes and Dataclasses
  • Python OOP Practice: Design a Bank, an Employee System and a Library
  • Set Up a Python AI Project with uv, VS Code and an API Key in .env
  • uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
  • Python try and except Basics: Catch an Error and Keep Going
  • Read and Write a File in Python: open, with, Modes and Encoding
  • Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack
  • Python Logging and Debugging: Levels, Handlers, logger.exception and breakpoint()
  • Python File Modes, pathlib and Context Managers: x, r+, rb, Path and __enter__/__exit__
  • Python CSV, JSON and Large Files: csv, json, yield Pipelines, tomllib and pickle
  • Python Practice: Build a Log File Analyzer and a File Organizer
  • Python Project Structure for AI-Assisted Development: Packages, config.py and AGENTS.md
  • Regular Expressions in Python: search, findall, Groups and Greedy vs Lazy
  • Testing Python Code with pytest: assert, parametrize, fixtures and pytest.raises
  • Async Python: async def, await, asyncio.gather and the Blocking Trap
  • Django, FastAPI or Flask? The Same Blog Feature in Three Shapes, and How to Choose
  • One Blog, Three Frameworks: Routing, Models, Templates and Layout in Django, FastAPI and Flask
  • Getting Started with Flask: Routes, Jinja2 Templates and WSGI in One Small App
  • Your First Flask App with uv: From an Empty Folder to a Page in Debug Mode
  • Flask Routes, Templates and url_for: Converters, Forms, Redirects and the Signed Session
  • Flask-SQLAlchemy Models and Flask-Migrate: From a Python Class to a Real Table
  • Building a Blog with an AI Coding Agent: Plan Mode, a Master Prompt and the First Review
  • Handing a Figma Design to an AI Agent: Compare the Files, Then Review the Change
  • Inside a Flask Blog: The App Factory, Blueprints, the Instance Folder and CORS Done Right
  • How a Request and a Login Flow Through a Flask Blog: Flask-Login, CSRF and the Signed Session
  • Testing a Flask Blog with pytest: A Test App from the Factory, Fixtures and the Test Client
  1. Blog
  2. /
  3. Python
  4. /
  5. Modules, Files and Errors

Python try and except Basics: Catch an Error and Keep Going

An exception is the object Python creates when something goes wrong. Catch it with try and a named except, read it with as, add else and finally, retry bad input in a loop, and see why a bare except hides your bugs.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Modules, Files and Errors

What you will learn

  • Explain what an exception is and why an unhandled one stops the program
  • Catch ValueError, ZeroDivisionError and KeyError with a named except
  • Read the error object with as, and use else and finally
  • Retry bad input in a loop, and avoid the bare except

Before you start

  • Python basics: variables, int() and dictionaries
  • Reading a traceback

So far, when something goes wrong, your program just stops. try and except let it deal with the problem and carry on. The rest of this section leans on that, so it's worth getting it clear.

A program that breaks

text = "abc"
number = int(text)
print("Got", number)
print("Done")
Traceback (most recent call last):
  File "S04L00_1_TryExcept\crash_no_try.py", line 2, in <module>
    number = int(text)
ValueError: invalid literal for int() with base 10: 'abc'

On line 2, int(text) tries to turn the letters into a number, and it can't. So Python creates an object that describes the problem. That object is called an exception; this one is a ValueError. Nothing in the code is ready for it, so the program stops right there, and "Got" and "Done" never print. An exception that nobody handles ends the whole program.

The courier's note

A courier has three steps at every house: ring the bell, hand over the parcel, get a signature. Today nobody's home. With no plan, the courier gives up, and the round is over with every other parcel still in the van. So the office adds a note: "if nobody's home, leave it with a neighbour". Now when the problem comes up at the first step, the courier skips the other two, follows the note, and carries on to the next stop. The steps are try, the note is except, and the note names the one problem it's for.

Flow of try and except: lines in try run in order; if one raises ValueError, the rest of try is skipped and the matching except runs; either way the program continues after the block try: number = int(text) print("Got", number) fails except ValueError: print(...) print("Done") jump, skip the rest No error: except is passed over and the program still reaches "Done".
When a line inside try fails, Python jumps to the matching except, then carries on after it.

Catching the error

text = "abc"

try:
    number = int(text)
    print("Got", number)
except ValueError:
    print("That is not a number")

print("Done")
That is not a number
Done

int(text) fails with the same ValueError. This time Python looks at the except line and asks: is this a ValueError? It is, so it matches. print("Got", ...) is skipped, and we land inside except. When except finishes, the program carries on from the line after it. Same bad text, but this time the program reaches the end.

Change text to "42" and nothing fails:

text = "42"

try:
    number = int(text)
    print("Got", number)
except ValueError:
    print("That is not a number")

print("Done")
Got 42
Done

The except block only runs when something inside try fails.

Every problem has its own name

def share(total, people):
    return total / people


try:
    print(share(100, 4))
    print(share(100, 0))
    print("All shared")
except ZeroDivisionError:
    print("Nobody to share with")
25.0
Nobody to share with

You can't divide by zero, so inside the function Python creates a ZeroDivisionError. The function has no try of its own, so the error comes back out to the line that called it, and that line is inside our try. So a try around a call also catches what goes wrong inside that function.

prices = {"tea": 20, "coffee": 35}

try:
    print(prices["tea"])
    print(prices["juice"])
except KeyError:
    print("We do not sell that")
20
We do not sell that

"juice" isn't a key, so Python creates a KeyError. Notice that 20 stays printed: whatever ran before the error has already happened.

What went wrongException
int("abc"), bad text for a numberValueError
100 / 0ZeroDivisionError
prices["juice"], a missing keyKeyError

Look inside the error with as

try:
    int("12x")
except ValueError as err:
    print("Message:", err)
    print("Kind:", type(err).__name__)
Message: invalid literal for int() with base 10: '12x'
Kind: ValueError

An exception is an object, so you can look inside it. as err gives it a name. Printing it gives Python's own message, and type(err).__name__ gives the kind of error as text. You don't have to guess what went wrong.

else and finally

def read_number(text):
    try:
        number = int(text)
    except ValueError:
        print("Not a number:", text)
    else:
        print("Number is", number)
    finally:
        print("Checked", text)


read_number("7")
read_number("seven")
Number is 7
Checked 7
Not a number: seven
Checked seven

With "7", nothing fails, so except is passed over and else runs. With "seven", except runs and else is skipped. finally runs both times. That's why people use them: else lets try hold only the risky line, and finally is for whatever must happen either way.

A loop that asks again

while True:
    print("Enter your age:")
    text = input()
    try:
        age = int(text)
    except ValueError:
        print("Please type digits only")
    else:
        break

print("Age saved:", age)

In the lesson the four answers "abc", an empty line, "7x" and "29" were passed in ahead of time, so the output shows the questions and messages but not the answers:

Enter your age:
Please type digits only
Enter your age:
Please type digits only
Enter your age:
Please type digits only
Enter your age:
Age saved: 29

int fails on empty text too. When "29" works, else runs and break leaves the loop. With try inside a loop, a bad answer doesn't end the program; it just asks again.

Check first, or just ask?

settings = {"theme": "dark"}

if "font" in settings:
    print(settings["font"])
else:
    print("Check first: no font set")

try:
    print(settings["font"])
except KeyError:
    print("Just ask: no font set")
Check first: no font set
Just ask: no font set

Same result. When the check is one simple line like this, either is fine. When it's hard to check ahead, like whether some text is a valid number, just try it and catch the error.

The bare except hides bugs

text = "42"

try:
    print(int(text) + totl)
except:
    print("Bad number")
Bad number

The number is fine. totl is a typo, so Python raises a NameError, and an except with no name after it (a bare except) catches everything. The message is wrong, and your typo is now hidden. Name the error you expect:

text = "42"

try:
    print(int(text) + totl)
except ValueError:
    print("Bad number")
Traceback (most recent call last):
  File "S04L00_1_TryExcept\bare_fixed.py", line 4, in <module>
    print(int(text) + totl)
                      ^^^^
NameError: name 'totl' is not defined

A NameError doesn't match, so nothing catches it, and the traceback points right at totl. AI tools sometimes write a bare except. Look for it when you read their code, or add one line to your prompt: "catch only the errors you expect".

Quick recap

  • An exception is the object Python creates when something goes wrong. With no try, it stops the program.
  • except SomeError catches that one kind; as err lets you read it.
  • else runs when there was no error; finally always runs.
  • Never use a bare except; it hides typos.

When you want your own error types and more control, go on to custom exceptions and advanced handling.

Try it yourself

Write to_age(text) that turns text into a number. Put try and except ValueError around it, print a helpful message for bad text, and return None. One solution prints this for "31" and "thirty":

31
'thirty' is not a whole number
None

Tried the exercise? Share your answer or ask a question.

The StudyEasy AI Community is free to join, with the lesson files, notebooks and code.

Join free on Skool

Keep going in Python · 27 of 48

Previous
uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project
Next post
Read and Write a File in Python: open, with, Modes and Encoding

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Related posts

Set Up a Python AI Project with uv, VS Code and an API Key in .env

One environment for every AI project: uv brings Python 3.12 and pinned packages from uv.lock, a check script fails four times on plain python and passes after uv sync, VS Code points at .venv, the API key stays in .env, and a stand-in test model answers when there is no key.

uv and pyproject.toml: Start, Add, Run and Rebuild a Python Project

One tool instead of venv, activate, pip install and pip freeze. Build a small chatbot project with uv init, hit ModuleNotFoundError, fix it with uv add, read pyproject.toml and uv.lock, then delete .venv and rebuild it with uv sync.

Read and Write a File in Python: open, with, Modes and Encoding

Make your data outlive the program: write notes.txt with open and with, read it back three ways, see how w wipes a file and a appends, why encoding matters, and what to do when a file isn't there.

Python Custom Exceptions and Advanced Error Handling: raise, raise from and the Call Stack

raise sends an error and except receives it. Follow an error up the call stack, use the exception family tree, re-raise and chain errors with raise from, and build InsufficientFundsError and an AppError family of your own.

On this page

  • A program that breaks
  • The courier's note
  • Catching the error
  • Every problem has its own name
  • Look inside the error with as
  • else and finally
  • A loop that asks again
  • Check first, or just ask?
  • The bare except hides bugs
  • Quick recap
  • Try it yourself
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

The Python Architect Masterclass: Full Stack to AI Engineer

Python, Django, FastAPI, React, Docker, AWS, LLMs, RAG, agents and MCP, from first steps to AI engineer.View on Udemy ↗: The Python Architect Masterclass: Full Stack to AI Engineer (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.