java - 自动关闭并抛出异常

标签 java try-with-resources method-invocation autocloseable

AutoCloseable 有一个方法“void close throws Exception”。 有些人建议扩展此接口(interface)并重写 close 方法并删除异常。例如,请参阅下面的链接。

但是当我忘记将该语句放入 try-with-resources 语句中时,是否会调用 close 方法?

  • 在 try-with-resources 中调用 close
  • 在流 API 中调用 close
  • 例如,当离开创建资源的方法时,由 java 自动执行???

其他信息 我在互联网上搜索并查看了文档。两人都建议删除 throws Exception 语句。但我对这个建议的 react 是,当将来我们项目中的某人实现新接口(interface)(无一异常(exception))并忘记将它们放入 try-with-resource 中时,我们就会发生资源泄漏。对于我们的项目来说,这不是一个大问题,因为我们使用的是 SonarQube,它会提到资源泄漏

示例位置:

最佳答案

The AutoCloseable has a method 'void close throws Exception'. Some suggest to extend this interface and override the close method and remove the Exception.

您发布的链接并不表明一般情况下,它向您展示了为什么 io 包有自己的 Closeable 接口(interface),该接口(interface)仅抛出 IOException(因为它不需要抛出更通用的Exception。)这在运行时造成零差异,它纯粹就位,因此如果有任何东西试图抛出某些东西,就会抛出编译器错误使用 io.Closeable 接口(interface)时,这不是 IOException。

But when i forget to put the statement in a try-with-resources statement is the close method than not called?

您似乎在暗示此处没有链接 - AutoCloseable 可能抛出的异常类型实际上与它包装的资源关闭时没有任何关系。

In the try-with-resources the close is called

是的,这就是语言功能的全部要点。

In the stream api the close is called

除非您将其包装在 try with resources block 中,否则不会。

Automatically by java when for instance leaving the method in which the resource is created???

不,如果您忘记关闭某个资源,它只会保持打开状态。

(此规则的唯一异常(exception)是,资源在终结器中关闭自身,该终结器在垃圾收集之前执行。但这当然不是值得依赖的东西,它只是(有时)用作后备。)

关于java - 自动关闭并抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51095867/

相关文章:

java - 确切的重载解决程序 - 为什么 f(1) 调用 f(int...arg) 和 f(long...arg) 没有歧义?

JavaScript Date 对象总是在 America/New_York 时区打印?

java - HibernateSearch ElasticSearch集成错误: Exception in thread "main" java. lang.ExceptionInInitializerError

java - Java Play! 是否有审计工具?框架

java - 如何计算该算法的时间复杂度

java - 为什么看起来调用了错误的方法?

java - 在 try-with-resources block 中调用对象的方法

java - 什么是抑制异常?

java - 为什么 Try-With-Resources 不会每次都创建一个新实例

jsf - 点击 bean 方法并重定向 GET 请求