Java 18 是否已弃用 try-finally?
在即将发布的 Java 18 中发布的 JEP 421 不赞成终止。我理解这意味着 finalize()
方法已被弃用。然而,它还提到了 try/finally 块并提到了 try-with-resources 作为替代方案,所以我很困惑 - 这是说 try/finally 将被弃用吗?我们是否应该开始更改遗留代码以用 try-with-resources 替换 try/finally ?
我认为这个 JEP 只是关于 finalize()
方法,但互联网上的一些页面(例如 https://metebalci.com/blog/what-is-new-in-java-18/) 说 try/finally 正在已弃用,这听起来有点令人震惊。
JEP 421, being released in the forthcoming Java 18, deprecates finalization. I understand this mean the finalize()
method is being deprecated. However, it also mentions the try/finally
block and mentions try-with-resources as an alternative, so I'm confused - is it saying that try/finally will be deprecated? Should we start changing our legacy code to replace try/finally with try-with-resources?
I thought that this JEP was only about the finalize()
method, but some pages on the internet (such as https://metebalci.com/blog/what-is-new-in-java-18/) are saying that try/finally is being deprecated, which sounds a bit alarming.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果可以的话,您当然应该更喜欢 try-with-resources,因为它更简洁,并且避免了忘记关闭可自动关闭资源的可能性,但是,
finally
不会消失。JEP 在错误使用的上下文中提到了
finally
。除了使用 try-with-resources 构造之外,您还可以嵌套两个 try/finally 块来修复错误,正如 JEP 指出的那样:“此处的修复涉及嵌套的 try-finally 构造,并留给读者作为练习。 ”You should certainly prefer try-with-resources when you can, since it is more concise and avoids the possibility of forgetting to close an autocloseable resource, but no,
finally
is not going away.The JEP mentions
finally
in a context where it is used incorrectly. Besides using a try-with-resources construct, you could nest two try/finally blocks to fix the error, as the JEP notes: "The fix here involves a nested try-finally construct, and is left as an exercise for the reader."