JAVA - Zero to Hero / File Handling

Handling File Exceptions

⚠️ What is a File Exception?

When working with files in Java (like reading, writing, creating), things can go wrong — the file might:

  • Not exist ❌

  • Be inaccessible 🔒

  • Be already created or locked 🔄

  • Be in a wrong path 🛣️

Java handles such problems using exceptions — and you must handle them using try-catch blocks.


🧱 Common File-Related Exceptions

Exception

Description

IOException

General input/output error (e.g., can't create/write/read a file)

FileNotFoundException

Trying to read a file that doesn't exist

SecurityException

No permission to access a file

NullPointerException

Working with a null file object


1️⃣ Example 1: Handling IOException during file creation

import java.io.File;
import java.io.IOException;

public class CreateFile {
    public static void main(String[] args) {
        File file = new File("example.txt");

        try {
            if (file.createNewFile()) {
                System.out.println("File created: " + file.getName());
            } else {
                System.out.println("File already exists.");
            }
        } catch (IOException e) {
            System.out.println("An error occurred while creating the file.");
            e.printStackTrace(); // Shows the actual error details
        }
    }
}

🧠 Explanation:

  • A File object is created to represent a file named example.txt.

  • The program tries to create the file using createNewFile().

  • If the file is created successfully, a message is printed confirming the creation.

  • If the file already exists, a message says so.

  • If there's an error (like permission issues or invalid path), an IOException is caught.

  • The catch block displays a custom error message and prints the error details using e.printStackTrace()


2️⃣ Example 2: Handling FileNotFoundException during reading

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class ReadFile {
    public static void main(String[] args) {
        try {
            File file = new File("data.txt");
            Scanner reader = new Scanner(file);

            while (reader.hasNextLine()) {
                String data = reader.nextLine();
                System.out.println(data);
            }

            reader.close();
        } catch (FileNotFoundException e) {
            System.out.println("File not found. Please check the filename.");
            e.printStackTrace();
        }
    }
}

🧠 Explanation:

  • A File object is created to represent data.txt.

  • A Scanner is used to read the contents of the file line by line.

  • hasNextLine() checks if more lines are present in the file.

  • nextLine() reads and stores each line as a String.

  • Each line is printed to the console.

  • After reading, the Scanner is closed using reader.close().

  • If the file does not exist, a FileNotFoundException is caught.

  • The catch block prints a friendly message and the actual error details using e.printStackTrace().


3️⃣ Example 3: Catching multiple exceptions

try {
    // File operations
} catch (FileNotFoundException e) {
    System.out.println("File not found.");
} catch (IOException e) {
    System.out.println("Input/output error.");
}

🧠 Explanation:

  • The try block contains file-related operations (like reading, writing, creating).

  • If the file is not found, FileNotFoundException is caught, and a message is shown.

  • If a general input/output error occurs (e.g., can't read/write), IOException is caught.

  • Each catch block handles a specific type of error, so your program doesn't crash.

  • This is an example of multi-catch to handle different possible exceptions separately.


🔐 Tip: Always close your file resources

Use .close() for Scanner, FileWriter, etc. Or use try-with-resources for auto-close:

try (Scanner reader = new Scanner(new File("data.txt"))) {
    // Read file
} catch (FileNotFoundException e) {
    // Handle error
}

📝 Summary

Keyword

Purpose

try

Wrap risky code that might cause an exception

catch

Handles the exception if it occurs

IOException

General error while creating/writing/reading

FileNotFoundException

File doesn't exist during read operation

e.printStackTrace()

Shows detailed error message (useful for debugging)