Tag: autocloseable

为什么try-with-resources catch块选择性地可选?

我读到try-with-resources中的catch块是可选的。 我尝试在try-with-resources块中创建一个Connection对象,没有后续的catch块,只是为了从eclipse中获取编译器错误:“自动close()调用引发的未处理的exception类型SQLException 。” 由于可以在try-with-resources中使用的每个资源都实现了AutoCloseable ,因此在调用close()方法时可能抛出exception,我不明白catch子句是如何可选的,因为它不允许我跳过从close()捕获exception。 是否有一些特殊要求, AutoCloseable的具体实现不直接声明其close()方法中抛出的任何exception? (例如,重写AutoCloseable的close() throws Exception一个带有close()exception,它不会抛出任何exception)? ..或者这可能只是一个日食问题? 编辑:这是仍然触发问题的最简单的代码片段: try (Connection con = dataSource.getConnection()) { /*…*/ } 关于这是否与使用JNDI数据源有关的想法? 提前致谢。

AutoCloseable的close方法抛出exception是否有意义? 应如何处理?

在C#中,在IDisposable的Dispose方法中抛出exception被认为是不好的做法 。 相比之下,在java中, AutoCloseable的close方法允许抛出任何exception并强制调用者以某种方式处理它。 但如果发生这种情况,合理预期的调用者会怎样做? 这表明关闭资源的尝试以某种方式失败了。 那么用户在继续之前是否必须尝试再次关闭资源,可能是某种指数退避?

Eclipse不一致:资源泄漏:”永远不会关闭

如果我有以下代码: public OutputStream test(boolean condition) throws FileNotFoundException { return condition ? null : new FileOutputStream(“test.txt”); } Eclipse将黄色曲线放在new FileOutputStream(“test.txt”)并向我显示以下警告: Resource leak: ” is never closed 奇怪的是,如果我删除三元操作: public OutputStream test() throws FileNotFoundException { return new FileOutputStream(“test.txt”); } 警告消失了。 这是Eclipse中的不一致(错误?)还是我错过了两种情况之间的一些根本区别? 一般来说,似乎Eclipse足够聪明,可以理解当我从方法返回一个Closeable ,可以不让方法关闭流(总之,返回一个封闭流的重点是什么?)。 当我间接返回结果时,它甚至可以正确地执行此操作: public OutputStream test() throws FileNotFoundException { FileOutputStream result = new FileOutputStream(“test.txt”); return result; } (这里没有警告) […]

幂等方法的含义是什么,以及在调用java.lang.AutoCloseable的close方法时有什么副作用?

java.lang.AutoCloseable的close()方法的Java文档说 * Note that unlike the {@link java.io.Closeable#close close} * method of {@link java.io.Closeable}, this {@code close} method * is not required to be idempotent. In other words, * calling this {@code close} method more than once may have some * visible side effect, unlike {@code Closeable.close} which is * required to have no effect […]