You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何无法将Lambda表达式内联传入try-with-resources语句?

问题原因解析

核心问题:受检异常未处理

AutoCloseable接口的close()方法签名是:

void close() throws Exception

这是一个受检异常,要求任何调用该方法的代码必须捕获异常,或是在方法签名中声明抛出它。

为什么单独赋值Lambda没问题,try-with-resources不行?

  • 仅将Lambda赋值给AutoCloseable变量时,编译器只检查Lambda是否匹配接口的单抽象方法签名,不会强制处理异常——因为此时并未实际调用close()方法。
  • 但在try-with-resources上下文里,JVM会自动隐式调用close()方法,这时编译器会检测到该受检异常未被处理,因此抛出编译错误。

你的Lambda代码() -> System.out.println("Closing")本身不会抛出异常,但由于AutoCloseable的close()方法声明了抛出Exception,编译器默认认为该Lambda实现的close()方法可能抛出Exception,所以必须进行处理。

解决方法

有两种方式修复编译错误:

  1. 在main方法上声明抛出Exception:
class Main {
  public static void main(String[] args) throws Exception {
    try (AutoCloseable test = () -> System.out.println("Closing")) {}
  }
}
  1. 添加catch块捕获Exception:
class Main {
  public static void main(String[] args) {
    try (AutoCloseable test = () -> System.out.println("Closing")) {}
    catch (Exception e) {
      // 可在此添加异常处理逻辑
    }
  }
}

内容的提问来源于stack exchange,提问作者flamasterrr

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 03:22:34