UncheckedIOException Carries IOException Through Streams

Checked IOException cannot cross a stream lambda; wrap it in UncheckedIOException at the boundary and unwrap the cause where the consumer handles it.

JavaResilience

Code

snippet
import java.io.IOException;
import java.io.UncheckedIOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class CheckedBridge {

    // 流管道里只能传非受检异常:边界处把 IOException 包进 UncheckedIOException
    static List<String> readConfig(Path file) {
        try {
            return Files.readAllLines(file, StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    public static void main(String[] args) throws IOException {
        Path config = Files.createTempFile("config-", ".ini");
        Files.write(config, List.of("mode=beta", "retries=3"));

        long settingCount = readConfig(config).stream()
                .filter(line -> line.contains("="))
                .count();
        System.out.println("settings: " + settingCount);

        // 消费端再拆包还原:cause 是原始的受检异常
        try {
            readConfig(Path.of("missing.ini"));
        } catch (UncheckedIOException e) {
            System.out.println("cause class: " + e.getCause().getClass().getSimpleName());
        }
        Files.deleteIfExists(config);
    }
}

What the code does

UncheckedIOException Carries IOException Through Streams keeps everything in the class CheckedBridge and the function readConfig.

The transformation runs as a stream pipeline — source, intermediate operations, terminal collector — so each stage stays independently readable. The failure path is explicit — UncheckedIOException is raised when the guard condition holds.

Caveats

  • No lockfile entry, no version pinning — the file needs nothing beyond the runtime.

Applying it

Entry signature: static List<String> readConfig(Path file)

The file announces its steps in the output: settings:, cause class:.

main calls 1 helper in sequence: readConfig.

Statements that matter most here

return Files.readAllLines(file, StandardCharsets.UTF_8);
throw new UncheckedIOException(e);
long settingCount = readConfig(config).stream()
        .filter(line -> line.contains("="))
        .count();

Interactive Tools for This Topic

FAQ

What happens on invalid input?
Validation comes first — `UncheckedIOException` marks the failure, before any partial work happens.
What does UncheckedIOException Carries IOException Through Streams print when run?
Execute the whole file; each printed line is prefixed with a label like `settings:`, `cause class:`.