Why Do File Exceptions Occur?
When a program tries to open, read from, write to, or delete a file, many things can go wrong. For example:
- The file might not exist.
- You might not have permission to access the file.
- The file could be locked by another process.
- The disk might be full or disconnected.
If your program doesn’t anticipate and handle these errors, it may crash. Exception handling ensures that your program can respond gracefully.
What Is File Exception Handling?
It’s the practice of using try-catch blocks (or equivalent) to detect and handle errors during file operations.
Basic Structure of File Exception Handling
TRY
Open the file
Read or Write to file
Close the file
CATCH FileNotFoundError
Show message: "The file was not found."
CATCH PermissionError
Show message: "Access denied to the file."
CATCH GenericError
Show message: "An unexpected error occurred."
FINALLY
Clean up resources (if needed)
Example 1: Reading a File That May Not Exist
Suppose we want to read from a file named "data.txt". If the file doesn’t exist, we want to handle that gracefully.
TRY
Open file "data.txt" in read mode
Read content from file
Print the content
CATCH FileNotFoundError
Print "File not found. Please check the file name."
FINALLY
Close file if it was opened
Output:
File not found. Please check the file name.
Question:
What happens if you try to read a file that doesn’t exist and you don't use a try-catch block?
Answer: The program crashes with an error like "File not found" and halts execution immediately.
Example 2: Handling Write Permission Error
Let’s say we try writing to a file in a location where we don’t have permission (e.g., system folder).
TRY
Open file "/restricted/log.txt" in write mode
Write "Log entry" to file
CATCH PermissionError
Print "Cannot write to the file. Permission denied."
CATCH GenericError
Print "Something went wrong."
Output:
Cannot write to the file. Permission denied.
Question:
Can we have multiple catch blocks for different error types?
Answer: Yes! Catch blocks can be stacked to handle different errors differently. This is good practice because it makes your code more robust.
Example 3: Always Cleaning Up Using Finally
What if an error occurs after opening a file but before closing it? The FINALLY
block ensures the file is always closed.
TRY
Open file "log.txt"
Write important log data
// Simulate error here
THROW Exception
CATCH GenericError
Print "Something went wrong."
FINALLY
Close file to prevent resource leak
Output:
Something went wrong. File closed successfully.
Key Takeaways
- Always expect something might go wrong with file operations.
- Use try-catch to prevent crashes.
- Use finally to clean up, like closing files.
- Handle specific errors when possible for better messages.
Mini Quiz
Q1: What block runs even if an error doesn't occur?
A1: The FINALLY
block.
Q2: Should you write file closing logic inside the try block?
A2: No. Use the finally block to ensure the file is always closed.