UncheckedIOException
An unchecked wrapper around `IOException`, needed where checked exceptions are not allowed, such as in lambdas.
Available since: Java 8
Syntax
public class UncheckedIOException extends RuntimeException
public UncheckedIOException(String message, IOException cause)Parameters
| Parameter | Type | Description |
|---|---|---|
| message | String | The error text. |
| cause | IOException | The original checked exception. |
Examples
An I/O error inside a lambda:
String read(Path p) {
try {
return Files.readString(p);
} catch (IOException e) {
throw new UncheckedIOException("Cannot read " + p, e);
}
}
void main() {
try {
Stream.of("missing.txt").map(Path::of).map(this::read).toList();
} catch (UncheckedIOException e) {
IO.println(e.getMessage());
IO.println(e.getCause().getClass().getSimpleName());
}
}Output:
Cannot read missing.txt
NoSuchFileExceptionNotes
Functional interfaces such as Function do not declare throws, so a lambda cannot throw IOException. The fix is to wrap it in UncheckedIOException together with the original cause. Files.lines() and BufferedReader.lines() throw this exception themselves on a read error.
See also
- IOException — A checked exception for input and output errors: files, network, data streams.
- Throwable.getCause() — Returns the original exception wrapped by the current one.
- -> (lambda) — A lambda expression — a short function that can be passed around as a value.
In the tutorial
- Checked and unchecked exceptions — Checked and unchecked exceptions in Java — what the compiler requires, the throws clause, RuntimeException and wrapping exceptions.