Python Error Handling Code Snippets: Try-Except Examples
Ready-to-use Python error handling code snippets. Copy-paste examples for common error handling patterns and exception management.
Python Error Handling Code Snippets
Collection of practical Python error handling code snippets for common scenarios. Copy and adapt these examples for your projects.
Basic Try-Except Structure #
try:
# Risky operation
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
except Exception as e:
print(f"Unexpected error: {e}")
finally:
print("This always runs")
File Operations Error Handling #
def safe_file_read(filename):
try:
with open(filename, 'r') as file:
content = file.read()
return content
except FileNotFoundError:
print(f"File '{filename}' not found")
return None
except PermissionError:
print(f"Permission denied to read '{filename}'")
return None
except Exception as e:
print(f"Error reading file: {e}")
return None
# Usage
content = safe_file_read("data.txt")
if content:
print("File content:", content)
User Input Validation #
def get_integer_input(prompt):
while True:
try:
value = int(input(prompt))
return value
except ValueError:
print("Please enter a valid integer")
except KeyboardInterrupt:
print("\nOperation cancelled")
return None
# Usage
age = get_integer_input("Enter your age: ")
if age is not None:
print(f"Your age is {age}")
Network Request Error Handling #
import requests
def safe_api_call(url):
try:
response = requests.get(url, timeout=5)
response.raise_for_status() # Raises HTTPError for bad responses
return response.json()
except requests.exceptions.Timeout:
print("Request timed out")
return None
except requests.exceptions.ConnectionError:
print("Connection error occurred")
return None
except requests.exceptions.HTTPError as e:
print(f"HTTP error: {e}")
return None
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
return None
# Usage
data = safe_api_call("https://api.example.com/data")
if data:
print("API response:", data)
Dictionary Safe Access #
def safe_dict_access(data, key, default=None):
try:
return data[key]
except KeyError:
print(f"Key '{key}' not found")
return default
except TypeError:
print("Data is not a dictionary")
return default
# Alternative using get() method (recommended)
def safer_dict_access(data, key, default=None):
if isinstance(data, dict):
return data.get(key, default)
else:
print("Data is not a dictionary")
return default
# Usage
user_data = {"name": "John", "age": 30}
email = safe_dict_access(user_data, "email", "No email provided")
print(f"Email: {email}")
List Index Error Handling #
def safe_list_access(lst, index, default=None):
try:
return lst[index]
except IndexError:
print(f"Index {index} is out of range")
return default
except TypeError:
print("Object is not indexable")
return default
# Better alternative using bounds checking
def safer_list_access(lst, index, default=None):
if isinstance(lst, (list, tuple)) and 0 <= index < len(lst):
return lst[index]
else:
return default
# Usage
numbers = [1, 2, 3, 4, 5]
value = safe_list_access(numbers, 10, "Not found")
print(f"Value: {value}")
Database Connection Error Handling #
import sqlite3
def safe_database_operation(db_path, query, params=None):
connection = None
try:
connection = sqlite3.connect(db_path)
cursor = connection.cursor()
if params:
cursor.execute(query, params)
else:
cursor.execute(query)
if query.strip().lower().startswith('select'):
result = cursor.fetchall()
else:
connection.commit()
result = cursor.rowcount
return result
except sqlite3.Error as e:
print(f"Database error: {e}")
return None
except Exception as e:
print(f"Unexpected error: {e}")
return None
finally:
if connection:
connection.close()
# Usage
result = safe_database_operation(
"example.db",
"SELECT * FROM users WHERE age > ?",
(25,)
)
if result:
print("Query result:", result)
JSON Parsing Error Handling #
import json
def safe_json_parse(json_string):
try:
return json.loads(json_string)
except json.JSONDecodeError as e:
print(f"Invalid JSON format: {e}")
return None
except TypeError:
print("Input must be a string")
return None
def safe_json_file_load(filename):
try:
with open(filename, 'r') as file:
return json.load(file)
except FileNotFoundError:
print(f"JSON file '{filename}' not found")
return None
except json.JSONDecodeError as e:
print(f"Invalid JSON in file: {e}")
return None
# Usage
json_data = '{"name": "John", "age": 30}'
parsed = safe_json_parse(json_data)
if parsed:
print("Parsed data:", parsed)
Custom Exception Classes #
class ValidationError(Exception):
"""Custom exception for validation errors"""
pass
class DataProcessingError(Exception):
"""Custom exception for data processing errors"""
pass
def validate_email(email):
if "@" not in email:
raise ValidationError("Invalid email format")
return True
def process_user_data(data):
try:
validate_email(data.get("email", ""))
# Process data here
return {"status": "success", "data": data}
except ValidationError as e:
return {"status": "validation_error", "message": str(e)}
except DataProcessingError as e:
return {"status": "processing_error", "message": str(e)}
except Exception as e:
return {"status": "unknown_error", "message": str(e)}
# Usage
user_info = {"name": "John", "email": "invalid-email"}
result = process_user_data(user_info)
print(f"Processing result: {result}")
Error Logging Pattern #
import logging
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
def logged_operation(func):
"""Decorator for logging errors"""
def wrapper(*args, **kwargs):
try:
result = func(*args, **kwargs)
logging.info(f"{func.__name__} completed successfully")
return result
except Exception as e:
logging.error(f"Error in {func.__name__}: {e}")
raise
return wrapper
@logged_operation
def risky_function(x, y):
return x / y
# Usage
try:
result = risky_function(10, 0)
except ZeroDivisionError:
print("Division by zero handled")
Usage Tips #
- Catch specific exceptions first, then general ones
- Always include error messages for debugging
- Use finally blocks for cleanup operations
- Consider using context managers for resource management
- Log errors in production applications
- Validate inputs before processing
- Provide meaningful default values when appropriate
These snippets provide robust error handling patterns that you can adapt to your specific needs. Choose the approach that best fits your use case and always test your error handling code.