相关疑难解决方法(0)

为什么Java的try-with-resource需要声明

Java7的try-with-resources非常棒,但是我无法理解为什么需要在try语句中包含资源声明.我的直觉说以下应该是可能的:

CloseableResource thing;
try (thing = methodThatCreatesAThingAndDoesSomeSideEffect()) {
    // do some interesting things
}
thing.collectSomeStats();
Run Code Online (Sandbox Code Playgroud)

唉,这会导致语法错误(密码期待a ;).将类型定义/声明移动到try语句中是有效的,这当然会将事物移动到相应的范围中.我想知道如何解决这个问题,当我想要更多AutoClosable关闭而不是关闭时,我对编译器为什么需要它这样感兴趣.

java try-catch

14
推荐指数
2
解决办法
4155
查看次数

标签 统计

java ×1

try-catch ×1