Python file exception handling

In Python, exceptions can be handled while working with files using try, except, and optionally finally. This is useful to catch potential errors such as FileNotFoundError, PermissionError, or IOError

Example:


try:
    with open("filename.txt", "r") as file:
        content = file.read()
        print(content)
except FileNotFoundError:
    print("Error: The file was not found.")
except PermissionError:
    print("Error: You do not have permission to access this file.")
except IOError:
    print("Error: An IO error occurred while handling the file.")

Explanation

FileNotFoundError: Raised when trying to open a file that does not exist.

PermissionError: Raised if there is a permission issue, such as trying to read a write-protected file.

IOError: A more general exception for input/output errors (covers cases like disk issues).

Using finally to Ensure File Closure

In cases where you need to manually handle file opening and closing (not using with), you can use finally to ensure the file is closed even if an exception occurs.


try:
    file = open("filename.txt", "r")
    content = file.read()
    print(content)
except FileNotFoundError:
    print("Error: The file was not found.")
except PermissionError:
    print("Error: You do not have permission to access this file.")
except IOError:
    print("Error: An IO error occurred while handling the file.")
finally:
    if 'file' in locals() and not file.closed:
        file.close()
        print("File closed successfully.")

Handling Multiple Errors

You can handle multiple specific errors or use a general Exception for unexpected issues.


try:
    with open("filename.txt", "r") as file:
        content = file.read()
except (FileNotFoundError, PermissionError) as e:
    print(f"Error: {e}")
except Exception as e:
    print(f"An unexpected error occurred: {e}")