Sub topic 10
Handling I/O Errors
This chapter assumes basic Java syntax, Path and Files, try/catch, and checked exceptions. File operations depend on the operating system, permissions, file contents, and file availability. Your program must handle failures instead of assuming every operation succeeds.
Understanding `IOException`
IOException is a checked exception that represents a failure while reading, writing, opening, or manipulating a file. Methods such as Files.readString and Files.writeString declare it, so the calling method must catch it or declare it with throws.
Several more specific exceptions extend IOException:
| Exception | Common cause | Useful response |
|---|---|---|
| `NoSuchFileException` | The path does not exist | Report a missing file or use a default |
| `AccessDeniedException` | The process lacks permission | Ask for permission or choose another path |
| `FileAlreadyExistsException` | Creation was requested but the file exists | Choose a different name or open differently |
| `DirectoryNotEmptyException` | A non-empty directory was deleted | Remove its contents first, if appropriate |
Catch a specific exception before its parent type. Otherwise, the parent catch block handles the error first.
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
public class ErrorDemo {
public static void main(String[] args) {
Path file = Path.of("missing.txt");
try {
String text = Files.readString(file);
System.out.println(text);
} catch (NoSuchFileException e) {
System.out.println("File not found: " + e.getFile());
} catch (AccessDeniedException e) {
System.out.println("Permission denied: " + e.getFile());
} catch (IOException e) {
System.out.println("File operation failed: " + e.getMessage());
}
}
}The first catch handles the most specific failure. The final catch handles other I/O failures that the program does not identify separately.
Choosing between `catch` and `throws`
Catch an exception when the current method can recover or give the user a useful response. For example, an application might display a default configuration when a settings file is missing.
Use throws IOException when a higher-level method should decide what to do. This is common in small command-line programs and helper methods:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class Reader {
static String load(Path path) throws IOException {
return Files.readString(path);
}
public static void main(String[] args) {
try {
System.out.println(load(Path.of("notes.txt")));
} catch (IOException e) {
System.err.println("Could not load notes.txt");
e.printStackTrace();
}
}
}printStackTrace is useful during development because it shows where the failure occurred. Production programs usually log the exception with context and avoid exposing internal paths to end users.
Errors that are not `IOException`
Some path and file failures are unchecked exceptions. InvalidPathException can occur when a string cannot be converted into a valid path for the operating system. SecurityException can occur when a security policy rejects an operation. Do not use IOException handling as if it covered every possible failure.
Exercise
Why must NoSuchFileException be caught before IOException?
Show answer
NoSuchFileException is a subclass of IOException. Catching IOException first would handle the error before the specific catch block could run.