Course contentsShow
← Java
Lesson 2053 of 2,87041. NIO.2 and the Path APIFree lesson

Exception Handling for File Read/Write Operations

Handle IOException and other exceptions that occur during file reading and writing operations.

Exception Handling for File Read/Write Operations

You'll learn how to properly catch and handle exceptions that occur when reading from or writing to files using NIO.2.

The Core Idea

File operations are inherently risky—files might not exist, you might lack permissions, the disk could be full, or encoding issues might arise. The NIO.2 API signals these problems by throwing IOException and its subclasses. Proper exception handling isn't optional; it's essential for writing robust file-handling code.

Think of file I/O like ordering delivery: the restaurant might be closed (file doesn't exist), the driver might get lost (permission denied), or they might run out of food (disk full). Your code needs to gracefully handle these scenarios rather than crashing.

Common Exceptions

IOException is the parent class for most file operation errors. Specific subclasses include:

  • NoSuchFileException: File doesn't exist when reading
  • FileAlreadyExistsException: File exists when you expected it not to
  • AccessDeniedException: Insufficient permissions

Handling Exceptions

Always wrap file operations in try-catch blocks or use try-with-resources:

try {
    String content = Files.readString(Paths.get("data.txt"));
    System.out.println(content);
} catch (NoSuchFileException e) {
    System.err.println("File not found: " + e.getMessage());
} catch (AccessDeniedException e) {
    System.err.println("Permission denied: " + e.getMessage());
} catch (IOException e) {
    System.err.println("I/O error: " + e.getMessage());
}

Notice the order: catch specific exceptions before the more general IOException.

When writing, handle potential issues similarly:

try {
    Files.writeString(Paths.get("output.txt"), "Hello");
} catch (IOException e) {
    System.err.println("Failed to write file: " + e.getMessage());
}

Key Takeaway: Always handle IOException and its subclasses when performing file operations; catch specific exceptions first for targeted error handling, and use try-catch or try-with-resources to ensure your program responds gracefully to file system errors.