广告
返回顶部
首页 > 资讯 > 后端开发 > Python >关于Java中的try-with-resources语句
  • 647
分享到

关于Java中的try-with-resources语句

Javatry-with-resourcesJavatry块 2023-05-19 14:05:40 647人浏览 八月长安

Python 官方文档:入门教程 => 点击学习

摘要

目录介绍语法介绍 try-with-resources是Java中的环绕语句之一,旨在减轻开发人员释放try块中使用的资源的义务。 它最初在Java 7中引入,背后的全部想法是,开发

介绍

try-with-resources是Java中的环绕语句之一,旨在减轻开发人员释放try块中使用的资源的义务。

它最初在Java 7中引入,背后的全部想法是,开发人员无需担心仅在一个try-catch-finally块中使用的资源的资源管理。这是通过消除对finally块的依赖而实现的。

此外,使用try-with-resources的代码通常更清晰易读,因此使代码更易于管理,尤其是当我们处理许多try块时。

语法

try-with-resources的语法与通常try-catch-finally语法相同。

普通try:

BufferedWriter writer = null;
try {
    writer = new BufferedWriter(new FileWriter(fileName));
    writer.write(str);  // do something with the file we've opened
} catch (ioException e) {
   // handle the exception
} finally {
    try {
        if (writer != null)
            writer.close();
    } catch (IOException e) {
       // handle the exception
    }
}

try-with-resources:

try(BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))){
    writer.write(str); // do something with the file we've opened
}
catch(IOException e){
    // handle the exception
}

Java理解此代码的方式:

try语句之后在括号中打开的资源仅在此处和现在需要。.close()在try块中完成工作后,将立即调用它们的方法。如果在try块中抛出异常,无论如何我会关闭这些资源。

注意

从Java 9开始,没有必要在try-with-resources语句中声明资源。

可以这样做:

BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
try (writer) {
    writer.write(str); // do something with the file we've opened
}
catch(IOException e) {
    // handle the exception
}

到此这篇关于关于Java中的try-with-resources语句的文章就介绍到这了,更多相关Java try-with-resources语句内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: 关于Java中的try-with-resources语句

本文链接: https://www.lsjlt.com/news/213309.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作