Java 18 是否已弃用 try-finally?

发布于 2025-01-10 02:40:18 字数 529 浏览 0 评论 0原文

在即将发布的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

岁月流歌 2025-01-17 02:40:18

如果可以的话,您当然应该更喜欢 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."

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文