Video in progress
Why is IOException a checked exception, and how should you catch it properly?
IO deals with the outside world: a full disk, a vanished file, a dropped network are always possible, so the compiler makes you think about this case. When you catch it, don't swallow the error: either handle it, or rethrow it upward with context.
📖 Answer
The worst option, and the one you often see on prod:
try {
Files.writeString(path, data);
} catch (IOException e) {
e.printStackTrace(); // or nothing at all
}
The data was not written, but the program carries on as if nothing happened.
Better:
try {
Files.writeString(path, data);
} catch (IOException e) {
throw new UncheckedIOException("Hisobotni yozib bo'lmadi: " + path, e);
}
IOException has useful subclasses: NoSuchFileException, AccessDeniedException, FileAlreadyExistsException. You can catch them separately and return an answer the user can understand.
You can't throw a checked exception inside a lambda, so in streams it is often wrapped in UncheckedIOException. Files.lines does exactly this internally.
Sign up to mark studied questions and save your progress.