Here's a function that reads a file with comprehensive exception handling:
def read_file(file_path):
try:
with open(file_path, 'r') as file:
content = file.read()
return content
except FileNotFoundError:
print(f"Error: The file '{file_path}' was not found.")
return None
except PermissionError:
print(f"Error: Permission denied to access '{file_path}'.")
return None
except IOError as e:
print(f"Error: An I/O error occurred: {e}")
return None
except Exception as e:
print(f"Error: An unexpected error occurred: {e}")
return None
Here's a more advanced version that offers additional features:
def read_file(file_path, mode='all', encoding='utf-8'):
"""
Read a file with proper exception handling.
Args:
file_path (str): Path to the file
mode (str): 'all' for entire file, 'lines' for list of lines
encoding (str): File encoding (default: utf-8)
Returns:
str/list: File content or None if error occurs
"""
try:
with open(file_path, 'r', encoding=encoding) as file:
if mode == 'lines':
content = file.readlines()
else:
content = file.read()
return content
except FileNotFoundError:
print(f"Error: The file '{file_path}' was not found.")
return None
except PermissionError:
print(f"Error: Permission denied to access '{file_path}'.")
return None
except UnicodeDecodeError:
print(f"Error: Unable to decode the file with {encoding} encoding.")
return None
except IOError as e:
print(f"Error: An I/O error occurred: {e}")
return None
except Exception as e:
print(f"Error: An unexpected error occurred: {e}")
return None
Usage examples:
# Read entire file
content = read_file('example.txt')
if content is not None:
print(content)
# Read file line by line
lines = read_file('example.txt', mode='lines')
if lines is not None:
for line in lines:
print(line.strip())
# Read file with different encoding
content = read_file('example.txt', encoding='latin-1')
if content is not None:
print(content)
Key features of this implementation:
-
Uses context manager (with statement) for proper file handling
-
Handles specific exceptions separately:
FileNotFoundError: When file doesn't exist
PermissionError: When user lacks permission
UnicodeDecodeError: When encoding issues occur
IOError: For input/output related errors
- General
Exception: For unexpected errors
-
Returns None on error to allow error checking in calling code
-
Supports different reading modes (whole file or line by line)
-
Allows specification of file encoding
-
Includes docstring with function documentation
This implementation provides robust error handling while remaining flexible for different use cases. You can modify the error messages or add additional exception handling based on your specific needs.