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}")

Python file exception handling – Interview Questions

Q 1: Why is exception handling needed in file operations?

Ans: To avoid runtime errors when files are missing or inaccessible.

Q 2: Which keyword is used for exception handling?

Ans: try and except.

Q 3: Can you catch multiple exceptions?

Ans: Yes, by specifying multiple exception types.

Q 4: How do you handle file not found error?

Ans: Use except FileNotFoundError: block.

Q 5: Can the finally block be used with file handling?

Ans: Yes, to ensure the file is closed regardless of errors.

Python file exception handling – Objective Questions (MCQs)

Q1. Which statement is used to handle exceptions in file operations?






Q2. What error is raised if you try to open a non-existent file in "r" mode?






Q3. How do you ensure a file is always closed, even after exceptions?






Q4. Which exception handles all input/output errors in files?






Q5. What will this code do?

try:
f = open("file.txt", "r")
except FileNotFoundError:
print("File not found")






Related Python file exception handling Topics