本文介绍了尝试资源:必须抛出或捕获close()方法的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果错误,请更正我:在Java 7的try-with-resources语句中,资源的 close()方法抛出的任何异常都必须声明为抛出通过我的方法,或者我必须将另一个 try 中的整个尝试包装起来,它捕获由 close()引发的任何异常。 / p>

如果是这样,我不得不怀疑我会不会使用它。我肯定不想要 throw close()抛出的异常,调用者不知道做到这一点并且尝试包装另一个尝试只是为了处理 close()至少不会看起来很优雅。



编辑:我想我不小心问了两个问题,其中一个是重复的



问题1.我必须声明我的方法从 close()方法中抛出异常,将try-with-resources包装在另一个尝试中? (在建议的副本中未回答)



问题2.有没有办法静默关闭资源? (显然是一个重复的,所以我把这个句子拿出来了,希望这个问题令人满意的是唯一的。)

解决方案

报价来自:

所以,基本上,包装器已经实现了


Please correct me if this is wrong: In Java 7's try-with-resources statement, any exceptions thrown by the resource's close() method must be either declared as thrown by my method or I must wrap the whole try in another try which catches any exceptions thrown by close().

If so, I have to wonder if I will make much use of it. I certainly don't want to throw the exceptions thrown by close(), the caller won't know what to do with that. And a try wrapping another try just to handle close() would not look very elegant, to me at least.

EDIT: I think I accidentally asked two questions, one of which was a duplicate.

Question 1. Do I have to declare that my method throws the exception from the close() method or wrap the try-with-resources in another try? (Not answered in proposed duplicate.)

Question 2. Is there a way to close the resource silently? (Clearly a duplicate, so I am taking that sentence out of the question. Hopefully this makes the question satisfactorily unique.)

解决方案

Quote from Java Language Specification ($14.20.3.2):

So, basically, wrapper is already implemented

这篇关于尝试资源:必须抛出或捕获close()方法的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 08:13