6.5 Error Handling

6.5 Error Handling

Understanding common exceptions like FileNotFoundError and PermissionError, and how to use try-except blocks to write robust code.

File management is one of the most error-prone operations in a program. The file you are trying to read may not exist, you may not have the necessary access permissions, or the disk may be full. Using `try-except` blocks is absolutely essential for writing robust code that does not crash unexpectedly.

Common File Exceptions

  • `FileNotFoundError`: The most common one. It occurs when you try to open a file for reading (`"r"`) that does not exist.
  • `PermissionError`: Occurs when your program does not have the operating system permissions to read, write, or create a file in a specific location.
  • `FileExistsError`: Occurs when you try to create a file with the `"x"` (exclusive creation) mode, but the file already exists.
  • `IsADirectoryError`: Occurs when you try to open a directory (folder) as if it were a file.
# Example of handling FileNotFoundError
try:
    with open("non_existent_file.txt", "r") as f:
        print(f.read())
except FileNotFoundError:
    print("Error: The file was not found. Please check the name and path.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

print("-" * 30)

# Example of handling FileExistsError with mode 'x'
try:
    # Create the file the first time
    with open("unique_file.txt", "w") as f:
        f.write("test")
    
    # The second time this runs, the 'x' will fail
    with open("unique_file.txt", "x") as f:
        f.write("This will not be written.")
except FileExistsError:
    print("Error: The file 'unique_file.txt' already exists and cannot be created with mode 'x'.")
except Exception as e:
    print(f"Unexpected error: {e}")

Practical Exercises

Explore More with AI

Use AI to generate new examples, delve deeper into theory, or get your questions answered.