Write a function to read a file with proper exception handling.
- User
Write a function to read a file with proper exception handling.
Assistant
Here's a clean function to read a file with proper exception handling:
def read_file(file_path): """ Read a file with comprehensive error handling. Args: file_path (str): Path to the file to read Returns: str: File content, or None if an error occurs """ try: with open(file_path, 'r', encoding='utf-8') as file: return file.read() except FileNotFoundError: print(f"Error: File '{file_path}' not found.") return None except PermissionError: print(f"Error: Permission denied accessing '{file_path}'.") return None except UnicodeDecodeError: print(f"Error: Cannot decode file '{file_path}' with UTF-8 encoding.") return None except Exception as e: print(f"Error: Unexpected error reading '{file_path}': {e}") return None # Usage example content = read_file('example.txt') if content is not None: print("File read successfully!") print(content) else: print("Failed to read file.")
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.