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

Handling IOException During Tree Walking

Managing errors via visitFileFailed and deciding whether to continue or abort traversal on exceptions.

Handling IOException During Tree Walking

You'll learn how to gracefully manage I/O errors that occur while traversing file trees using the FileVisitor's error-handling mechanism.

Understanding Error Scenarios

When walking a file tree, things can go wrong: a file might be deleted mid-traversal, you might lack permissions to read a directory, or a network drive could disconnect. Rather than crashing your entire operation, NIO.2 lets you decide how to respond to these problems.

The visitFileFailed Method

The FileVisitor interface includes a special method specifically for error handling:

FileVisitResult visitFileFailed(Path file, IOException exc)

This method gets called automatically whenever an IOException occurs while trying to access a file or directory. You control what happens next by returning a FileVisitResult:

  • CONTINUE: Log the error but keep walking the rest of the tree
  • TERMINATE: Stop the entire traversal immediately
  • SKIP_SUBTREE: Not applicable here (used in preVisitDirectory)
  • SKIP_SIBLINGS: Skip remaining files in the current directory

Example: Resilient Directory Counter

class ResilientCounter extends SimpleFileVisitor<Path> {
    private int fileCount = 0;
    
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
        fileCount++;
        return FileVisitResult.CONTINUE;
    }
    
    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) {
        System.err.println("Cannot access: " + file + " - " + exc.getMessage());
        return FileVisitResult.CONTINUE; // Keep going despite errors
    }
}

This visitor counts accessible files while gracefully skipping problematic ones—like a delivery driver noting addresses they couldn't reach but completing the rest of the route.

Key Takeaway: Use visitFileFailed to handle I/O errors during tree traversal; return CONTINUE to log and proceed, or TERMINATE to stop immediately when errors are unacceptable.