What Is Error Handling in Python?
Error handling is the way a Python program deals with problems while it is running.
Instead of crashing as soon as something goes wrong, your code can respond in a controlled way. This is useful when working with user input, files, calculations, and other data that may not always be valid.
In Python, error handling is commonly done with try and except.
A quick example
Here is a simple example of error handling:
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 does:
- The code in
trymight fail. - If the user enters text like
"hello", Python raises aValueError. - If the user enters
0, Python raises aZeroDivisionError. - Instead of showing a long traceback, the program prints a clear message.
This is the basic idea of error handling: prepare for problems and respond safely.
What error handling means
Error handling is how a program deals with problems during runtime.
It helps your code:
- respond to errors instead of stopping suddenly
- show useful messages
- recover when possible
- stop safely when needed
In Python, these problems are usually called exceptions. If that term is new, see Python errors and exceptions explained.
Why error handling is useful
Error handling is useful because real programs often deal with unpredictable input and data.
It can help you:
- prevent the whole program from crashing on common mistakes
- show clear messages to the user
- continue running when that makes sense
- stop safely when continuing would cause bigger problems
This is especially important when working with:
- user input
- files
- web data
- external APIs
- calculations
Common situations where errors happen
Beginners often see errors in situations like these:
- converting text to a number with
int()orfloat() - opening a file that does not exist
- using a list index that is too large
- looking up a missing dictionary key
- dividing by zero
Examples:
- User enters text when a number is expected
- Program tries to open a missing file
- Code uses an invalid list index
- Program divides by zero
- Code accesses a missing dictionary key
Basic parts of Python error handling
Python gives you a few main tools for handling errors.
try
The try block contains code that may cause an error.
except
The except block runs if an error happens.
else
The else block runs only if no error happens in try.
finally
The finally block runs whether there is an error or not.
If you want the full syntax and examples, read using try, except, else, and finally in Python.
Beginner example to include
A common beginner example is asking the user for a number.
try:
number = int(input("Enter a number: "))
print("Double:", number * 2)
except ValueError:
print("That was not a valid whole number.")
What happens here
input()gives you textint()tries to convert that text to a whole number- if the text is not a valid number, Python raises
ValueError - the
exceptblock shows a friendly message
Example:
Input
abc
Output
That was not a valid whole number.
Without error handling, the program would stop and show a traceback.
Here is a second simple example with a file:
try:
with open("notes.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("The file was not found.")
If notes.txt does not exist, the program handles the problem instead of crashing. For more help with this specific problem, see FileNotFoundError in Python: causes and fixes.
Good beginner habits
When you start using error handling, these habits will help:
- catch specific errors when possible
- keep the
tryblock small - write messages that clearly explain what went wrong
- only handle errors you understand
For example, this is better:
try:
number = int(user_input)
except ValueError:
print("Please enter a valid number.")
Than this:
try:
number = int(user_input)
except:
print("Something went wrong.")
The first version is clearer and easier to debug.
Common beginner mistakes
Here are some common mistakes:
- using a bare
exceptfor everything - putting too much code inside
try - catching an error but doing nothing
- confusing syntax errors with runtime errors
A syntax error means your code is written incorrectly, so Python cannot run it.
An exception usually happens while the program is already running.
For example:
print("Hello"
This is a syntax error, not something you would normally handle with try and except.
What this page should not cover in depth
This page is only a definition and overview.
It does not go deep into:
- full
try/exceptsyntax - long lists of exception types
- advanced exception handling patterns
For practical usage, see how to use try-except blocks in Python or how to handle exceptions in Python.
If you need help with a specific error, go to pages such as ValueError in Python: causes and fixes or ZeroDivisionError in Python: causes and fixes.
Next steps for the reader
A good path forward is:
- learn what Python errors and exceptions are
- understand how
try,except,else, andfinallywork - visit specific error pages when solving a real problem
- learn how to raise exceptions in Python when you want your own code to signal a problem
Useful commands while learning:
python your_script.py
print(type(value))
print(value)
help(ValueError)
help(ZeroDivisionError)
These can help you inspect values and understand the error type you are seeing.
FAQ
Is error handling the same as fixing errors?
Not exactly. Error handling means your program is prepared for possible problems and responds safely when they happen.
What is the difference between an error and an exception?
Beginners often use the words loosely. In Python, an exception is the object raised when something goes wrong during runtime.
Should I use try-except everywhere?
No. Use it where errors are likely and where you know how to respond.
Why not use bare except?
It can hide the real problem and make debugging harder. Catch specific exception types instead.
Can a program continue after an error?
Yes, if the error is handled properly and your code knows what to do next.