Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to handle exception inside a Python for loop?
You can handle exceptions inside a Python for loop using try-except blocks. There are two main approaches: handling exceptions for each iteration individually, or handling exceptions for the entire loop.
Exception Handling Per Iteration
Place the try-except block inside the loop to handle exceptions for each iteration separately ?
for i in range(5):
try:
if i % 2 == 0:
raise ValueError(f"Error at iteration {i}")
print(f"Processing: {i}")
except ValueError as e:
print(f"Caught exception: {e}")
Caught exception: Error at iteration 0 Processing: 1 Caught exception: Error at iteration 2 Processing: 3 Caught exception: Error at iteration 4
Exception Handling for Entire Loop
Place the try-except block around the entire loop to catch any exception that breaks the loop ?
try:
for i in range(5):
if i == 3:
raise ValueError("Critical error - stopping loop")
print(f"Processing: {i}")
except ValueError as e:
print(f"Loop interrupted: {e}")
Processing: 0 Processing: 1 Processing: 2 Loop interrupted: Critical error - stopping loop
Practical Example with File Processing
Here's a real-world example processing a list of files where some might not exist ?
files = ['data1.txt', 'data2.txt', 'missing.txt', 'data3.txt']
for filename in files:
try:
# Simulate file reading
if filename == 'missing.txt':
raise FileNotFoundError(f"File {filename} not found")
print(f"Successfully processed: {filename}")
except FileNotFoundError as e:
print(f"Skipping file: {e}")
except Exception as e:
print(f"Unexpected error with {filename}: {e}")
Successfully processed: data1.txt Successfully processed: data2.txt Skipping file: File missing.txt not found Successfully processed: data3.txt
Comparison
| Approach | Exception Scope | Loop Behavior | Best For |
|---|---|---|---|
| Inside Loop | Per iteration | Continues after exception | Skip bad items, process rest |
| Outside Loop | Entire loop | Stops at first exception | Critical errors that should halt processing |
Conclusion
Use try-except inside the loop to handle individual iteration errors and continue processing. Use try-except outside the loop when any error should stop the entire operation.
Advertisements
