IOException
A checked exception for input and output errors: files, network, data streams.
Available since: Java 1.0
Syntax
public class IOException extends ExceptionExamples
Reading a missing file:
void main() {
try {
String text = Files.readString(Path.of("no-such-file.txt"));
IO.println(text);
} catch (NoSuchFileException e) {
IO.println("File not found: " + e.getMessage());
} catch (IOException e) {
IO.println("Read error: " + e.getMessage());
}
}Output:
File not found: no-such-file.txtNotes
It is a checked exception: a method that reads a file must either catch it or declare throws IOException. It has many subclasses — NoSuchFileException, FileNotFoundException, AccessDeniedException; a more specific catch goes above the general one.
See also
- UncheckedIOException — An unchecked wrapper around `IOException`, needed where checked exceptions are not allowed, such as in lambdas.
- try-with-resources — A `try` block that closes opened resources automatically — files, connections, streams.
- Exception — The base class of exceptions a program can catch and handle.
In the tutorial
- Checked and unchecked exceptions — Checked and unchecked exceptions in Java — what the compiler requires, the throws clause, RuntimeException and wrapping exceptions.