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

FileAlreadyExistsException and Error Handling

Handle common exceptions during copy/move operations: FileAlreadyExistsException, IOException, and AccessDeniedException.

FileAlreadyExistsException and Error Handling

What you'll learn: How to handle common exceptions that occur during file copy, move, and delete operations in NIO.2.

Why Exception Handling Matters

When working with file operations, things can go wrong: files might already exist at the destination, you might lack permission to access a file, or network issues might interrupt I/O. NIO.2 provides specific exception types to help you understand and respond to these failures appropriately.

Common File Operation Exceptions

FileAlreadyExistsException

Thrown when you attempt to create or copy a file to a location where a file already exists, and you haven't specified REPLACE_EXISTING:

try {
    Files.copy(sourcePath, targetPath);
} catch (FileAlreadyExistsException e) {
    System.out.println("File already exists at: " + e.getFile());
    // Handle: prompt user, use different name, or add REPLACE_EXISTING
}

IOException

The general superclass for I/O failures. Catch this for unexpected errors:

try {
    Files.move(sourcePath, targetPath);
} catch (IOException e) {
    System.err.println("I/O error: " + e.getMessage());
}

AccessDeniedException

Thrown when you lack permission to read, write, or delete a file:

try {
    Files.delete(path);
} catch (AccessDeniedException e) {
    System.out.println("Permission denied: " + e.getFile());
    // Handle: notify user, check permissions, or request elevation
}

Handling Multiple Exceptions

Use multi-catch blocks or exception hierarchies:

try {
    Files.copy(source, target);
} catch (FileAlreadyExistsException e) {
    // Specific handling for existing files
} catch (AccessDeniedException e) {
    // Specific handling for permission issues
} catch (IOException e) {
    // General I/O error handling
}

Key Takeaway: Always handle FileAlreadyExistsException, AccessDeniedException, and general IOException when performing file operations to create robust, user-friendly applications that gracefully respond to real-world filesystem conditions.