Handling File
Exceptions Gracefully



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:

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

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.



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

Mention your name, and programguru.org in the message. Your name shall be displayed in the sponsers list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M