Python Errors and Exceptions Explained
Python errors and exceptions are messages that tell you something went wrong in your code. As a beginner, these messages can look confusing at first, but they are actually very useful.
This page explains:
- what errors and exceptions are
- how Python behaves when it finds a problem
- how to read a traceback
- when to handle an exception with
tryandexcept - when you should fix the code instead
Once you can read what Python is telling you, those scary red messages turn into a map that points straight at the problem.
Quick example #
Use this pattern when user input or calculations might fail. It shows how exceptions can be caught without crashing the program.
try:
number = int(input("Enter a number: "))
print(10 / number)
except ValueError:
print("Please enter a valid whole number.")
except ZeroDivisionError:
print("You cannot divide by zero.")
What this code does:
int(input(...))can fail if the user types something like"hello"10 / numbercan fail if the user enters0except ValueErrorhandles bad number inputexcept ZeroDivisionErrorhandles division by zero
Without try and except, the program would stop with an error message.
What this page covers #
- Difference between an error and an exception in simple terms
- How Python stops when it hits a problem
- How to read a traceback and find the useful line
- When to handle exceptions and when to fix the code directly
What is an error in Python? #
An error means something went wrong in your code.
In beginner Python, “error” is often used as a general word for any problem. That problem might happen:
- before the program runs properly
- while the program is running
For example:
- a missing colon can cause a
SyntaxError - trying to use a variable that does not exist can cause a
NameError
When Python finds a problem, it usually shows:
- an error message
- a traceback
- the line where the problem happened
What is an exception? #
An exception is a runtime problem. That means it happens after Python has already started running your code.
Python raises an exception when it cannot continue normally.
For example:
ValueErrorTypeErrorKeyErrorIndexError
Many exceptions can be handled with try and except. If you want to learn that syntax in more detail, see using try-except, else, and finally in Python.
Example:
age = int("hello")
This raises a ValueError because "hello" is a string, but it is not a valid integer.
Errors before running vs errors during running #
Some problems happen before your code can run normally. Others happen while it is already running.
Errors before normal execution #
These happen when Python cannot understand your code.
Common examples:
SyntaxErrorIndentationError
Example:
if True
print("Hello")
Python will report a SyntaxError because the colon : is missing after True.
If you are dealing with this specific problem, see how to fix SyntaxError: invalid syntax.
Errors during running #
These happen after Python has started executing your code.
Common examples:
TypeErrorValueError
Example:
number = int("abc")
This starts running, but fails when Python tries to convert "abc" to an integer.
How to read a Python traceback #
A traceback is the block of text Python shows when an exception happens.
It tells you:
- where the error happened
- what kind of exception occurred
- sometimes why it happened
Example:
numbers = [10, 20, 30]
print(numbers[5])
You might see something like this:
Traceback (most recent call last):
File "example.py", line 2, in <module>
print(numbers[5])
IndexError: list index out of range
How to read it #
Start with the last line first:
IndexError: list index out of range
This tells you:
- the exception type is
IndexError - the message is
list index out of range
Then look above it:
File "example.py", line 2, in <module>
print(numbers[5])
This tells you:
- the file name
- the line number
- the exact line that failed
A good beginner method #
When reading a traceback:
- Read the last line first
- Find the file name and line number
- Look at that line in your code
- Check the values used on that line
- Look one or two lines above it for the real cause
If you see IndexError, this page may help next: fix IndexError: list index out of range.
Common exception types beginners should know #
Here are some of the most common exceptions you will see early on.
NameError #
This happens when you use a variable or function name that does not exist.
print(score)
If score was never created, Python raises a NameError.
See how to fix NameError: name is not defined.
TypeError #
This happens when you use the wrong data type in an operation.
print("Age: " + 25)
You cannot add a string and an integer directly, so Python raises a TypeError.
Related help: fix TypeError: unsupported operand type(s) for +.
ValueError #
This happens when the type is correct, but the value is not valid.
number = int("abc")
"abc" is a string, which int() can accept, but its value is not a valid integer.
See common ValueError causes and fixes.
IndexError #
This happens when you use a list position that does not exist.
colors = ["red", "blue"]
print(colors[3])
KeyError #
This happens when you use a dictionary key that does not exist.
user = {"name": "Sam"}
print(user["age"])
See why KeyError happens and how to fix it.
FileNotFoundError #
This happens when you try to open a file that does not exist at the given path.
with open("missing.txt", "r") as file:
print(file.read())
See FileNotFoundError causes and fixes.
ZeroDivisionError #
This happens when you divide by zero.
print(10 / 0)
Python cannot do that calculation, so it raises a ZeroDivisionError.
Basic exception handling #
Use try for code that might fail. Use except to handle a specific problem.
Example:
try:
age = int(input("Enter your age: "))
print("Next year you will be", age + 1)
except ValueError:
print("Please enter a valid number.")
How it works:
- Python runs the code inside
try - if a
ValueErrorhappens, Python jumps toexcept - the program shows a helpful message instead of crashing
Why this is useful #
Exception handling helps your program fail more gracefully.
This is especially helpful when working with:
- user input
- files
- dictionary keys
- list indexes
- number conversions
A broader practical guide is available here: how to handle exceptions in Python.
Handle specific exceptions #
Try to catch the exact exception you expect.
Good:
try:
number = int(user_input)
except ValueError:
print("That was not a valid number.")
Less helpful:
try:
number = int(user_input)
except:
print("Something went wrong.")
A bare except: catches almost everything, which can hide real bugs.
When not to use try-except #
Do not use try-except to hide mistakes in your code.
For example, this is not a good fix:
try:
print(total_price)
except:
pass
This hides the problem instead of solving it. If total_price was never defined, the real fix is to define it correctly.
Avoid broad except blocks unless you have a clear reason and you are handling the error properly.
Sometimes a simple check is clearer than exception handling.
Example:
numbers = [1, 2, 3]
if len(numbers) > 2:
print(numbers[2])
This can be easier to understand than catching an IndexError.
Beginner debugging steps #
When you get an error, use this simple process:
- Read the full message carefully
- Check the exact line number
- Print variable values before the failing line
- Reduce the code to a small example
- Test one fix at a time
Useful debugging commands #
These basic tools can help:
print(variable)
type(variable)
help(Exception)
dir(object)
What they do:
print(variable)shows the current valuetype(variable)shows the data typehelp(Exception)shows information about exceptionsdir(object)shows available attributes and methods
Common causes of errors #
Many beginner errors come from a small set of problems:
- typos in variable or function names
- wrong indentation
- using the wrong data type
- accessing missing list indexes or dictionary keys
- bad user input
- missing files or wrong file paths
- dividing by zero
What to learn next #
Once you understand the basics, the next step is to practice handling exceptions yourself.
A good path is:
- learn
tryandexceptsyntax in more detail - read the page for the exact error message you see
- learn common built-in exceptions one by one
- practice with small examples that trigger real errors
✍️ Try it yourself
Write code that asks for a list position and prints the item at that position in ["red", "blue"]. First make it crash with an IndexError by using position 5, then add a try/except IndexError so it prints a friendly message instead of showing a traceback.
Show answer
colors = ["red", "blue"]
position = 5
try:
print(colors[position])
except IndexError:
print("That position does not exist in the list.")
Output:
That position does not exist in the list.
FAQ #
What is the difference between an error and an exception in Python? #
An error is a general problem in code. An exception is a specific runtime problem that Python can raise while the program is running.
Is SyntaxError an exception? #
It is an error type reported by Python when the code cannot be parsed correctly. Beginners usually treat it as a code mistake found before normal execution.
Should I use try-except everywhere? #
No. Use it only where failure is expected or possible. If the code itself is incorrect, fix the code instead.
What part of the traceback should I read first? #
Start with the last line because it shows the exception type and message. Then check the line number in your code.
What are the most common Python exceptions for beginners? #
NameError, TypeError, ValueError, IndexError, KeyError, FileNotFoundError, and ZeroDivisionError.