Exception Handling in Python
Learn how to handle runtime errors and keep your Python programs running safely.
What is an Exception?
An exception is an error that occurs while a Python program is running.
When an exception occurs and is not handled, the program can stop and display an error message.
Why Do We Need Exception Handling?
Real applications can face many unexpected situations.
- A file may not exist.
- A user may enter invalid input.
- A calculation may cause an error.
- A database or network operation may fail.
Exception handling allows us to handle these situations in a controlled way instead of letting the program stop unexpectedly.
Exception Handling Diagram
The basic flow of exception handling can be understood like this:
Python Program
Normal program execution starts.
try Block
Code that may cause an exception.
No Exception
Program continues normally.
Exception Occurs
Control moves to the matching except block.
Exception Handling
Program handles the problem and can continue in a controlled way.
Simple Example
Consider a program that divides two numbers.
number1 = 10
number2 = 0
result = number1 / number2
print(result)
This program raises a
ZeroDivisionError because a number
cannot be divided by zero.
Output
ZeroDivisionError: division by zero
Handling the Exception
We can use try and except
to handle the problem.
try:
number1 = 10
number2 = 0
result = number1 / number2
print(result)
except ZeroDivisionError:
print("Cannot divide by zero")
Output:
Cannot divide by zero
Instead of stopping the program with an unhandled exception, we display a meaningful message.
Common Python Exceptions
| Exception | Common Cause |
|---|---|
ValueError
|
Invalid value for an operation. |
TypeError
|
Incompatible data types are used. |
ZeroDivisionError
|
Division by zero. |
FileNotFoundError
|
Requested file does not exist. |
IndexError
|
Invalid list or sequence index. |
KeyError
|
Requested dictionary key does not exist. |
Example: ValueError
A ValueError can occur when the data type
is acceptable but the actual value is not suitable
for the operation.
try:
age = int("abc")
print(age)
except ValueError:
print("Invalid number")
Output:
Invalid number
Example: TypeError
try:
result = "10" + 5
print(result)
except TypeError:
print("Incompatible data types")
Output:
Incompatible data types
Example: IndexError
numbers = [10, 20, 30]
try:
print(numbers[5])
except IndexError:
print("Invalid list index")
Output:
Invalid list index
Example: KeyError
student = {
"name": "Rahul",
"course": "Python"
}
try:
print(student["fees"])
except KeyError:
print("Key does not exist")
Output:
Key does not exist
Example: FileNotFoundError
try:
with open(
"students.txt",
"r"
) as file:
data = file.read()
print(data)
except FileNotFoundError:
print("File not found")
This is useful when a program tries to read a file that does not exist.
Exception Handling Flow
Step 1:
Put risky code inside try.
↓
Step 2: Python executes the code.
↓
Step 3:
If an exception occurs, Python looks for a
matching except block.
↓
Step 4: The matching exception handler runs.
↓
Step 5: Program continues according to the remaining code.
Benefits of Exception Handling
- Prevents unexpected program termination.
- Provides meaningful error messages.
- Makes applications more reliable.
- Helps separate normal logic from error handling.
- Makes debugging and maintenance easier.
Best Practices
Handle Specific Exceptions
Catch the exception you expect instead of hiding every possible error.
Give Clear Messages
Show useful information to the user or developer.
Keep try Blocks Small
Put only the code that may raise the expected exception inside the try block.
Accessing the Exception Message
We can store the exception object using
as and print its message.
try:
number = int("abc")
except ValueError as error:
print("Error:", error)
The variable error contains information
about the exception.
Handling a General Exception
Python also allows a general Exception
handler.
try:
result = 10 / 0
except Exception as error:
print("Error:", error)
A broad handler should be used carefully because it can catch many different exception types.
Example 📩
Suppose a student enters a number for marks.
try:
marks = int(
input("Enter marks: ")
)
print("Marks:", marks)
except ValueError:
print("Please enter a valid number")
If the user enters text instead of a number, the program handles the problem gracefully.
Output
Enter marks: 85
Marks: 85
Without vs With Exception Handling
| Without Handling | With Handling |
|---|---|
| Program can stop when an exception occurs. | Program can respond to the problem. |
| User may see a technical error. | Program can display a meaningful message. |
| Less control over failures. | Better control over expected failures. |
Common Mistakes
-
Putting the wrong code inside the
tryblock. - Catching the wrong exception type.
- Using an overly broad exception handler everywhere.
- Hiding the real problem with an unclear message.
- Using exceptions to replace normal program logic.
Practice Programs
- Handle division by zero.
- Handle invalid integer input.
- Handle invalid list index.
- Handle missing dictionary keys.
- Handle a missing file.
-
Display the exception message using
as error.
Exception Handling Topics in This Module
try & except
Handle common runtime errors.
Multiple Exceptions
Handle different exception types.
finally
Run cleanup code.
raise Exception
Manually raise an exception.
Custom Exceptions
Create your own exception classes.
Practice
Apply exception handling in programs.
Summary
Exception handling is used to manage runtime problems
in Python programs. The try block contains
code that may raise an exception, while the
except block handles the error. Python
provides different exception types such as
ValueError, TypeError,
IndexError, KeyError and
FileNotFoundError. Proper exception
handling makes programs more reliable and easier
to maintain.