Python Introduction to Exceptions
Table of Contents + −
In the last lesson you learned Iterating Through Dictionaries. You looped over data and trusted it would always be there in the right shape. But real programs deal with messy input. Sometimes things go wrong while the code is running. When that happens, Python raises an exception. This lesson is about what an exception is. It also explains why one can stop your whole program.
🤔 Why Exceptions Matter
Here is the pain. You write a program that asks for a number and divides by it. Someone types 0. Your code tries to divide by zero. That is not allowed in math. It is not allowed in Python either. So the program does not quietly continue. It stops right there and prints a block of red text.
That red text is Python telling you an exception happened. The fix is exception handling, and we start it in the next lesson. You catch the problem and let the program keep going instead of crashing.
But before we catch anything, you need to understand what an exception actually is.
🧩 What Is an Exception?
An exception is an error that happens while the program runs. Not when you write it. Not when Python first reads it. It happens while the code is actually running, line by line.
Think of it like cooking from a recipe. The recipe reads fine. The grammar is correct. But halfway through, the step says “add the eggs” and there are no eggs in the kitchen. You cannot keep going. You have to stop and deal with it. That missing-eggs moment is an exception. Everything looked okay until that exact step tried to run.
There are two very different kinds of problems in Python, and people often mix them up:
| Kind of problem | When it shows up | Example |
|---|---|---|
| Syntax error | Before the program runs at all | Forgetting a colon: if x == 5 |
| Exception | While the program is running | Dividing by zero, or int("hello") |
A syntax error means Python could not even read your code. An exception means your code read fine and started running. Then it hit a step it could not finish.
Note
“Raising an exception” just means Python ran into a problem and signalled it. You will hear “raised”, “thrown”, and “an exception occurred”. They all mean the same thing. Something went wrong mid-run.
💥 A Small Crash
Let’s see one for real. This program turns a piece of text into a number.
price = int("hello")print(price)We ask int() to turn the text "hello" into a whole number. But "hello" is not a number. There is no sensible number it could become. So Python cannot finish that step, and it raises an exception.
Here is exactly what Python prints, and then it stops:
Output
Traceback (most recent call last): File "shop.py", line 1, in <module> price = int("hello")ValueError: invalid literal for int() with base 10: 'hello'The program never reaches the print(price) line. The exception stopped everything the moment it happened. That is the part that hurts. One bad value, and the whole program is done.
🔎 Reading the Traceback
That red block is called a traceback. It looks scary, but it is just Python telling you the story of what went wrong. Read it from the bottom up. The most useful line is the last one.
Let’s name each part in plain words:
- “Traceback (most recent call last)” — the heading. It just says “here comes the report of where things broke”.
File "shop.py", line 1— the exact file and line number where the problem happened. This is where you go look.price = int("hello")— the actual line of code that failed, copied out for you.ValueError— the type of exception. This name tells you what kind of problem it was. Here, a value that did not make sense.invalid literal for int() with base 10: 'hello'— the message. Plain-ish English describing the problem. It is saying: “I tried to read'hello'as a base-10 number and could not.”
So the whole thing really answers four questions. Where did it break? What line broke? What type of error was it? And what was the message? Always read the last line first. It tells you the type and the message, which is usually enough to know what to fix.
Tip
The exception type is a strong clue. ValueError means the value was wrong for the operation. ZeroDivisionError means you divided by zero. TypeError means you used the wrong type, like adding a number to a piece of text. The name alone often points you straight at the bug.
⚙️ Another Common One: Dividing by Zero
Here is the divide-by-zero case, since it comes up so often. Imagine splitting a bill between people, and the number of people is somehow 0.
total = 240people = 0each = total / peopleprint(each)We try to share 240 between 0 people. There is no answer to that. So the division step fails, and Python raises an exception.
This is what runs, and then it stops:
Output
Traceback (most recent call last): File "bill.py", line 3, in <module> each = total / people ~~~~~^~~~~~~~ZeroDivisionError: division by zeroThe same shape as before. The last line gives you the type, ZeroDivisionError, and the message, division by zero. The line number points at each = total / people. On newer Python versions (3.11 and up) you also get a little ~~~~~^~~~~~~~ line that underlines the exact spot that broke. Older versions leave that line out. Once you can read this, you already know what to fix, even before you learn how to catch it.
⚠️ Common Mistakes
A few things trip people up early on:
- Mixing up syntax errors and exceptions. A syntax error stops Python before anything runs. An exception happens partway through a run. They are not the same problem.
- Reading the traceback from the top. The top is just the heading and the path through your code. The line you actually want is the last one. Read bottom-up.
- Ignoring the exception type name. People skim past
ValueErrororTypeError. That name is the single most useful word in the whole message. - Assuming user input is clean. A lot of exceptions come from real data. Someone types text where you expected a number, or a
0where you expected a count.
# ❌ Avoid: trusting that input is always a valid numberage = int(input("Your age: ")) # crashes if someone types "twenty"
# ✅ Good: know this CAN raise an exception, so you can plan to catch it# (catching it is the next lesson — for now, just see the risk)age = int(input("Your age: "))✅ Best Practices
Small habits make exceptions much less scary:
- Read the last line of the traceback first. The type plus the message is usually all you need.
- Use the line number in the traceback to jump straight to the broken line.
- Treat the exception type as a label for the bug. Learn the common ones:
ValueError,TypeError,ZeroDivisionError,KeyError. - Expect risky spots. Anything that turns text into a number, divides, or reads user input can raise an exception. Knowing where it can happen is most of the work.
🧩 What You’ve Learned
✅ An exception is an error that happens while your program runs, not when you write it.
✅ A syntax error stops Python before the run starts; an exception stops it partway through.
✅ An unhandled exception crashes the program and prints a traceback, so later code never runs.
✅ A traceback shows the file, the line number, the line of code, the exception type, and a message.
✅ Read the traceback from the bottom up; the last line names the type and the problem.
✅ Common types like ValueError and ZeroDivisionError tell you what kind of thing went wrong.
Check Your Knowledge
Test what you learned. Pick an answer for each question, then click Check.
- 1
When does an exception happen?
Why: An exception is a runtime error: the code read fine and started running, then hit a step it could not finish.
- 2
Which line of a traceback is usually the most useful to read first?
Why: Read bottom-up: the last line names the exception type and the message, which usually tells you what to fix.
- 3
What kind of exception does int("hello") raise?
Why: 'hello' is not a valid number, so int() raises a ValueError for an invalid value.
- 4
How is a syntax error different from an exception?
Why: Python cannot even read code with a syntax error, while an exception occurs partway through a running program.
🚀 What’s Next?
Now you know what an exception is and how to read the traceback it leaves behind. Next you will learn how to actually catch one, so your program keeps going instead of crashing.