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.
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.
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 wrong | Exception |
|---|---|
int("abc"), bad text for a number | ValueError |
100 / 0 | ZeroDivisionError |
prices["juice"], a missing key | KeyError |
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 SomeErrorcatches that one kind;as errlets you read it.elseruns when there was no error;finallyalways 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
NoneRelated 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.
