为什么我不能将 lambda 内联传递到 try-with-resources

问题描述 投票:0回答:1

帮助我理解为什么以下代码无法编译。 AutoCloseable 是一个单一的抽象方法接口,我可以将它分配给 lambda 表达式,只是不在 try-with-resources 上下文中:

class Main {
  public static void main(String[] args) {
    try (AutoCloseable test = () -> System.out.println("Closing")) {}
  }
}

我遇到了以下编译错误并试图解决问题 - 为什么?

错误:未报告的异常Exception;必须被抓获或宣告 被扔了

对资源隐式调用 close() 引发的异常 变量“测试”

java try-with-resources
1个回答
0
投票

使用

Closeable
代替
AutoCloseable

© www.soinside.com 2019 - 2024. All rights reserved.