Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

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

ParameterTypeDescription
messageStringThe error text.
causeIOExceptionThe 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
NoSuchFileException

Notes

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.

Thanks for reading!

Donate to the site — we work hard for you.