⬅ Previous Topic
Working with Text and Binary FilesNext Topic ⮕
Working with File Paths - Relative vs Absolute⬅ Previous Topic
Working with Text and Binary FilesNext Topic ⮕
Working with File Paths - Relative vs AbsoluteWhen a program tries to open, read from, write to, or delete a file, many things can go wrong. For example:
If your program doesn’t anticipate and handle these errors, it may crash. Exception handling ensures that your program can respond gracefully.
It’s the practice of using try-catch blocks (or equivalent) to detect and handle errors during file operations.
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)
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
File not found. Please check the file name.
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.
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."
Cannot write to the file. Permission denied.
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.
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
Something went wrong. File closed successfully.
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.
⬅ Previous Topic
Working with Text and Binary FilesNext Topic ⮕
Working with File Paths - Relative vs AbsoluteYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.