← 中文资源

简体中文版本

UncheckedIOException 跨 lambda 桥接受检异常

受检 IOException 不能穿过流管道:边界处包成 UncheckedIOException 往上传,消费端 getCause() 拆包还原原始异常。

阅读英文原文

实现说明

除了类 CheckedBridge和函数 readConfig,文件里再无其他定义。 stream 各阶段从左到右组合——终端操作执行之前什么都不会跑。非法状态在入口就被拒绝:抛出 UncheckedIOException,而不是带着坏数据继续。

使用要点

  • 演示输出是带标签的(settings:、cause class:),每个操作都会留下自己的一行标注。
  • main 的演示流程是 readConfig——跑一遍文件,这条流程从头到尾可见。

常见问题

输入非法时会怎样?

校验先行——UncheckedIOException 标记失败,不会先做一半再失败。

运行「UncheckedIOException 跨 lambda 桥接受检异常」会打印什么?

整个文件跑完,输出行以 settings:、cause class: 这类前缀开头。

主签名形如 static List<String> readConfig(Path file)

核心语句

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

代码示例

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);
    }
}