EXCEPTION HANDLING WITH FILE OPERATIONS

Exception handling is essential when working with file operations to handle potential errors that may occur during file handling. File operations, such as opening, reading, writing, or closing files, can encounter various issues like file not found, permissions errors, or unexpected content. Python provides a way to handle these errors gracefully using try-except blocks. Here's how you can perform exception handling with file operations:

1. Handling File Not Found Error:

python
file_path = "nonexistent_file.txt" try: with open(file_path, "r") as file: content = file.read() print(content) except FileNotFoundError: print("File not found!")

In this example, if the file "nonexistent_file.txt" is not found, a FileNotFoundError will be raised, and the except block will handle it by printing an error message.

2. Handling Permission Errors:

python
file_path = "protected_file.txt" try: with open(file_path, "w") as file: file.write("Hello, World!") except PermissionError: print("Permission denied! Unable to write to the file.")

If the file "protected_file.txt" is read-only or inaccessible due to permission restrictions, a PermissionError will be raised, and the except block will handle it by printing an error message.

3. Handling Other Exceptions:

You can use a more general except block to handle any other exceptions that may occur during file operations:

python
file_path = "my_file.txt" try: with open(file_path, "r") as file: content = file.read() print(content) except Exception as e: print(f"An error occurred: {e}")

In this case, any exception during file handling will be caught and handled by the except block, and it will print an error message along with the specific exception that occurred.

4. Using finally Block:

The finally block is used to execute code that should always run, regardless of whether an exception occurred or not. For example, you can use it to ensure that the file is properly closed after reading or writing:

python
file_path = "my_file.txt" try: with open(file_path, "r") as file: content = file.read() print(content) except FileNotFoundError: print("File not found!") except Exception as e: print(f"An error occurred: {e}") finally: print("Closing the file.")

In this example, the finally block will execute, whether an exception occurred or not, and it will print "Closing the file."

Using try-except blocks allows you to handle potential errors gracefully and provide appropriate feedback to users when dealing with file operations. It is essential to anticipate and handle exceptions to make your code robust and prevent unexpected crashes.