Error Handling: NoSuchFileException and AccessDeniedException
What You'll Learn
You'll learn how to catch and handle the two most common exceptions that occur when listing directories: when the directory doesn't exist or when you lack permission to read it.
Why Directory Operations Fail
When you attempt to list a directory's contents using DirectoryStream or Files.list(), Java doesn't silently ignore problems—it throws specific exceptions to tell you exactly what went wrong. Think of it like a librarian telling you "That section doesn't exist" versus "You're not authorized to browse that section."
The Two Key Exceptions
NoSuchFileException is thrown when you try to list a directory that simply doesn't exist on the filesystem. This is like asking for directions to a building that was never constructed.
AccessDeniedException occurs when the directory exists, but your process lacks the necessary read permissions. The directory is there, but you're locked out.
Handling These Exceptions
Always wrap directory listing operations in try-catch blocks to handle these scenarios gracefully:
Path dirPath = Paths.get("/some/directory");
try (DirectoryStream<Path> stream = Files.newDirectoryStream(dirPath)) {
for (Path entry : stream) {
System.out.println(entry.getFileName());
}
} catch (NoSuchFileException e) {
System.err.println("Directory does not exist: " + dirPath);
} catch (AccessDeniedException e) {
System.err.println("Access denied to directory: " + dirPath);
} catch (IOException e) {
System.err.println("Unexpected I/O error: " + e.getMessage());
}
Notice we catch the specific exceptions first, then fall back to the general IOException for any other file system issues.
Key Takeaway: Always catch NoSuchFileException and AccessDeniedException when listing directories to distinguish between missing directories and permission problems, allowing your application to respond appropriately to each situation.