Sub topic 10
Handling I/O errors
This chapter assumes you know basic Java syntax, checked exceptions with try/catch, and the Files read and write methods from earlier chapters. It covers which exceptions file operations throw, how to catch them in a useful order, and how to report failures without hiding the cause.
Why file code fails
Files live outside your program. Another process can delete a file after you checked it. A disk can fill up. A user can lack permission. A file can contain bytes that are not valid text. Because of this, almost every method in java.nio.file.Files declares throws IOException, and you cannot avoid handling it.
The goal is not to prevent every failure. The goal is to react to the failures you can fix, such as a missing file, and to let the rest reach a place that can report them properly.
The exception hierarchy
IOException is the checked base class. The java.nio.file package adds FileSystemException, which carries extra detail about the failure, and a set of subclasses for common cases.
FileSystemException offers three useful accessors: getFile() returns the path that failed, getOtherFile() returns the second path for copy and move operations, and getReason() returns an explanation from the operating system when one exists.
| Exception | Typical trigger |
|---|---|
| `NoSuchFileException` | `readString`, `newBufferedReader`, or `Files.delete` on a path that does not exist |
| `FileAlreadyExistsException` | `createFile`, or `copy` and `move` onto an existing target without `REPLACE_EXISTING` |
| `DirectoryNotEmptyException` | `Files.delete` on a directory that still has entries |
| `AccessDeniedException` | No permission to read, write, or delete. On Windows, also a file that another process holds open |
| `AtomicMoveNotSupportedException` | `move` with `ATOMIC_MOVE` where the file system cannot do it |
| `MalformedInputException` | Reading bytes that are not valid in the charset you chose |
Two more exception types are unchecked, so the compiler does not force you to handle them:
InvalidPathExceptioncomes fromPath.ofwhen the string is not a legal path on the current platform, for example one containing a NUL character.UncheckedIOExceptionwraps anIOExceptionthat occurs while a stream is being consumed. Section "Errors inside streams" covers it.
Catch specific exceptions first
Java picks the first catch block whose type matches. Subclasses must therefore come before IOException, or the code will not compile. This example catches a missing file separately:
import java.io.IOException;
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 {
System.out.println(Files.readString(file));
} catch (NoSuchFileException e) {
System.out.println("File not found: " + e.getFile());
} catch (IOException e) {
System.out.println("Read failed: " + e.getMessage());
}
}
}If missing.txt does not exist, the first handler runs and prints the path. Any other failure, such as a permission problem, reaches the general handler.
Handle a subclass only when you can do something specific about it. Typical recoveries are creating a default file, asking for a different path, or skipping an optional file. If you cannot recover, do not catch it at all. Declare throws IOException and let a caller higher up decide.
Do not check first, then act
A common pattern is if (Files.exists(p)) { read(p); }. This does not protect you. The file can disappear between the check and the read, so you still need the catch. With the check in place you also have two code paths for the same problem.
The same idea applies to creating files. Files.createFile fails with FileAlreadyExistsException if the file is already there, and that failure is atomic. It is a reliable way to claim a file name, which a check followed by a write is not.
Encoding failures
Reading text can fail even when the file opens normally. Files.readString and Files.readAllLines decode strictly. If the bytes are not valid in the charset, they throw MalformedInputException instead of substituting replacement characters.
import java.io.IOException;
import java.nio.charset.MalformedInputException;
import java.nio.file.Files;
import java.nio.file.Path;
public class BadEncoding {
public static void main(String[] args) throws IOException {
Path file = Path.of("latin1.txt");
// 0xE9 is "é" in ISO-8859-1 but is not valid UTF-8 on its own
Files.write(file, new byte[] {(byte) 0xE9, '\n'});
try {
Files.readString(file);
} catch (MalformedInputException e) {
System.out.println("Not valid UTF-8: " + e.getMessage());
}
}
}The fix is almost never to catch and ignore the error. Find out which charset the file really uses and pass it explicitly, for example Files.readString(file, StandardCharsets.ISO_8859_1). Catch MalformedInputException when your program accepts files from users and should report "this is not a UTF-8 text file" instead of a stack trace.
Note that MalformedInputException is not a FileSystemException. A catch (FileSystemException e) will not see it.
Errors inside streams
Streams from Files.lines, Files.walk and Files.list read the file while you consume the stream. Lambdas and stream operations cannot throw checked exceptions, so an IOException that occurs mid-stream is wrapped in UncheckedIOException. The original exception is available from getCause().
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.stream.Stream;
public class StreamErrors {
public static void main(String[] args) {
Path file = Path.of("notes.txt");
try (Stream<String> lines = Files.lines(file)) {
lines.forEach(System.out::println);
} catch (UncheckedIOException e) {
IOException cause = e.getCause();
System.out.println("Failed while reading: " + cause.getMessage());
} catch (IOException e) {
System.out.println("Could not open: " + e.getMessage());
}
}
}Both handlers are needed. Failing to open the file throws a plain IOException from Files.lines itself. A failure after reading has begun, such as invalid UTF-8 on line 500, surfaces as UncheckedIOException from the terminal operation. The try-with-resources block closes the stream in both cases.
Errors while closing and suppressed exceptions
close() can fail too, and for a writer it matters: buffered data may be flushed during close(), so a full disk can show up there and not in the earlier write call. Try-with-resources handles this correctly. If the body throws and close() also throws, the body's exception is the one you receive. The closing failure is attached to it and available from getSuppressed().
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
public class SuppressedDemo {
public static void main(String[] args) {
Path file = Path.of("out.txt");
try (BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
writer.write("data");
writer.newLine();
} catch (IOException e) {
System.err.println("Write failed: " + e);
for (Throwable t : e.getSuppressed()) {
System.err.println(" also: " + t);
}
}
}
}Do not replace try-with-resources with a manual finally that calls close(). A failure in close() there would replace the original exception and you would lose the root cause.
Reporting failures usefully
Three habits keep error handling from becoming a source of confusion:
- Keep the cause. When you wrap an exception, pass the original as the second constructor argument:
new IOException("Cannot load config " + path, e). Without it, the stack trace of the real failure is gone. - Add the context you have. A bare "Access denied" is much less helpful than one that names the operation and the path.
FileSystemException.getFile()gives the path when the exception already carries it. - Never leave a
catchblock empty. If you intend to ignore a failure, such as a best-effort cleanup, say so in a comment and log it at a low level.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class ConfigLoader {
static String load(Path path) throws IOException {
try {
return Files.readString(path);
} catch (IOException e) {
throw new IOException("Cannot load configuration from " + path, e);
}
}
public static void main(String[] args) {
try {
System.out.println(load(Path.of("app.conf")));
} catch (IOException e) {
System.err.println(e.getMessage());
System.err.println("Caused by: " + e.getCause());
}
}
}Common mistakes
- Catching
IOExceptionbeforeNoSuchFileException. This is a compile error because the second block is unreachable. - Forgetting that
Path.ofcan throwInvalidPathExceptionfor user-supplied strings. Validate or catch it at the boundary where the input enters. - Using
Files.deletewheredeleteIfExistsis wanted, then being surprised byNoSuchFileException. - Deleting a directory with
Files.deleteand gettingDirectoryNotEmptyException. The directory's contents must be removed first. - Assuming a successful
writecall means the data is on disk. The failure may appear atclose().
Exercise
A method reads a file with Files.lines(path) inside try-with-resources and calls .map(...) and .count() on the stream. The file exists, but line 12 contains bytes that are invalid UTF-8. Which exception does the caller see, where does it come from, and how do you get the underlying IOException?
Show answer
The caller sees UncheckedIOException, thrown while the terminal operation count() is reading lines, because the stream cannot throw a checked exception mid-pipeline. Its getCause() returns the original IOException, here a MalformedInputException. The file opened successfully, so Files.lines itself did not throw. The try-with-resources block still closes the stream.
Exercise
Why is if (Files.exists(p)) { text = Files.readString(p); } not a substitute for catching NoSuchFileException?
Show answer
The file can be deleted or renamed by another process between the check and the read, so readString can still throw. The check also does not cover other failures such as AccessDeniedException. Calling the operation and handling its exceptions covers all of these cases in one place.