What Is an Exception in Python?
An exception in Python is a problem that happens while your program is running.
When an exception happens, Python usually stops the normal flow of the program and shows an error message. In many cases, you can also handle the exception so your program responds in a better way instead of crashing.
A simple way to think about it:
- Your code starts running normally
- Something unexpected happens
- Python raises an exception
- You can either let it stop the program or handle it with
tryandexcept
A quick example
Here is a small example of an exception being handled:
try:
number = int("abc")
except ValueError:
print("That value cannot be converted to an integer")
Output:
That value cannot be converted to an integer
What this does:
int("abc")tries to turn the text"abc"into an integer- That is not possible, so Python raises a
ValueError - The
except ValueError:block catches that exception - Instead of crashing, the program prints a helpful message
What an exception means
An exception is:
- An error that happens while a program is running
- Something that interrupts normal execution
- A way for Python to report what went wrong
- Usually shown with an exception name and a traceback
Exceptions are different from syntax errors.
- A syntax error means the code itself is written incorrectly
- An exception means the code starts running, but a problem happens during execution
For a broader introduction, see Python errors and exceptions explained.
When exceptions happen
Exceptions happen in very common situations, such as:
- Using a bad list index
- Converting invalid text with
int() - Opening a file that does not exist
- Dividing by zero
- Looking up a missing dictionary key
Examples:
numbers = [10, 20, 30]
print(numbers[5]) # IndexError
print(int("hello")) # ValueError
print(10 / 0) # ZeroDivisionError
data = {"name": "Ana"}
print(data["age"]) # KeyError
Basic example
Here is code that raises an exception:
number = int("abc")
print(number)
If you run it, Python raises a ValueError because "abc" is not a valid integer.
Now compare that with a handled version:
try:
number = int("abc")
print(number)
except ValueError:
print("Please enter a number using digits only")
Output:
Please enter a number using digits only
How to read this:
trymeans: run this codeexceptmeans: if this specific error happens, do this instead
If you want to learn the full pattern, including else and finally, read using try, except, else, and finally in Python.
Why exceptions are useful
Exceptions are useful because:
- They prevent silent failures
- They give clear names such as
ValueErrororIndexError - They let programs respond to problems
- They help you debug by showing what caused the problem
Without exceptions, your program might fail in confusing ways. With exceptions, Python tells you:
- what went wrong
- where it happened
- often which type of problem it is
That makes fixing bugs much easier.
Exception vs error handling
These two ideas are related, but they are not the same:
- An exception is the problem itself
- Error handling is the code you write to deal with that problem
For example:
ValueErroris an exceptiontryandexceptare part of error handling
This page focuses on the term exception. For practical ways to catch and manage them, see how to handle exceptions in Python.
Common exception types beginners see
These are some of the most common exceptions in Python:
ValueErrorTypeErrorIndexErrorKeyErrorNameErrorFileNotFoundErrorZeroDivisionError
A few examples:
ValueError: the value is the wrong form, such asint("abc")TypeError: the type is wrong, such as adding a string to an integerIndexError: a list index does not existNameError: you use a variable that has not been definedFileNotFoundError: Python cannot find the file you asked for
You can read more about specific exceptions here:
- ValueError in Python: causes and fixes
- TypeError in Python: causes and fixes
- IndexError in Python: causes and fixes
- NameError in Python: causes and fixes
- FileNotFoundError in Python: causes and fixes
Common causes
Beginners often run into exceptions because of one of these problems:
- Using the wrong type of value in a function
- Accessing data that does not exist
- Working with missing files or invalid paths
- Doing math that is not allowed, such as division by zero
- Using variables before defining them
When you see an exception, read the exception name first. It usually gives the best clue about the problem.
Helpful debugging commands
These commands and tools can help you understand exceptions:
python your_file.py
Runs your Python file so you can see the full error message.
print(type(value))
Shows the type of a value, which helps with TypeError and ValueError.
print(value)
Shows the actual value being used.
help(int)
Displays help for int() so you can see how it works.
dir(object)
Shows available attributes and methods on an object.
FAQ
Is an exception the same as a syntax error?
No. A syntax error means the code is written incorrectly. An exception happens while correct-looking code is running.
Do exceptions always crash a program?
Not always. If you handle the exception with try and except, your program can continue or fail more clearly.
What is the difference between an exception and an error?
Beginners often use the words the same way. In Python, an exception usually means a runtime problem that Python can raise and you can handle.
What is the most common exception for beginners?
Common ones include ValueError, TypeError, IndexError, NameError, and FileNotFoundError.
See also
- Python errors and exceptions explained
- Using try, except, else, and finally in Python
- How to handle exceptions in Python
- ValueError in Python: causes and fixes
- TypeError in Python: causes and fixes
- IndexError in Python: causes and fixes
The next useful step is to learn how to catch exceptions with try and except, then look up the specific error type you are seeing.