java的try后面跟括号

您所在的位置:网站首页 java方法括号里面创建对象 java的try后面跟括号

java的try后面跟括号

2023-10-24 08:35| 来源: 网络整理| 查看: 265

     从jdk1.7之后,可以不需要写finally块来关闭资源,因为新增了一个接口AutoCloseable,该接口只有一个方法close()就是用来是关闭资源的,例如文件或者套接字资源,默认的是抛出Exception异常。

API对AutoClose接口的解释:

可以保存资源的对象(如文件或套接字句柄),直到它关闭。 AutoCloseable对象的close()方法在退出已在资源规范头中声明对象的try -with-resources块时自动调用。 这种结构确保迅速释放,避免资源耗尽异常和可能发生的错误。

    括号里的内容支持包括流以及任何可关闭的资源,数据流会在 try 执行完毕后自动被关闭,不用我们手动关闭了。

下面是一段参照代码

public static List listDirDto(String path) throws BaseAppException { logger.debug("SystemSftpHelper listDirDto start ..."); try (IFtpHelper ftpHelper = FtpFactory.buildFtpClient(buildFtpConnectionInfo())) { List folderDtoList = ftpHelper.qryDirListNotRec(path); logger.debug("SystemSftpHelper listDirDto end ..."); return folderDtoList; } catch (ZcampSftpException e) { logger.error("zcampSftpException happened", e); ExceptionHandler.publish(SystemErrorCode.SYSTEM_BLANK_EXCEPTION, "list ftp directory failed", e); } catch (Exception e) { logger.error("close sftp connection exception", e); ExceptionHandler.publish(SystemErrorCode.SYSTEM_BLANK_EXCEPTION, "close ftp connectin failed", e); } return null; }

参考:https://blog.csdn.net/NewReErWen/article/details/101047248

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3