如果这是错误的,请纠正我:在Java 7的try-with-resources语句中,资源close()方法抛出的任何异常都必须声明为我的方法抛出,或者我必须将整个try包装在另一个try捕获由异常引发的异常中close().
如果是这样,我不得不怀疑我是否会充分利用它.我当然不希望throw抛出异常close(),调用者不知道该怎么做.至少对我来说,try另一个try只是处理它的包装close()看起来不会很优雅.
编辑: 我想我不小心问了两个问题,其中一个是重复的.
问题1.我是否必须声明我的方法从方法中抛出异常close()或在另一次尝试中包装try-with-resources?(未在建议的副本中回答.)
问题2.有没有办法静默关闭资源?(显然是重复的,所以我不接受这个句子.希望这使得这个问题令人满意地独特.)
我正在阅读有关JDK7中的try-with-resource的内容,当我考虑将我的应用程序升级为使用JDK7运行时,我遇到了这个问题.
当使用BufferedReader时,例如写入抛出IOException和close抛出IOException ..在catch块中我关注写入引发的IOException ..但我不会太在意关闭抛出的那个..
数据库连接和任何其他资源的问题相同..
作为一个例子,我创建了一个自动关闭资源:
public class AutoCloseableExample implements AutoCloseable {
public AutoCloseableExample() throws IOException{
throw new IOException();
}
@Override
public void close() throws IOException {
throw new IOException("An Exception During Close");
}
}
Run Code Online (Sandbox Code Playgroud)
现在使用它时:
public class AutoCloseTest {
public static void main(String[] args) throws Exception {
try (AutoCloseableExample example = new AutoCloseableExample()) {
System.out.println(example);
throw new IOException("An Exception During Read");
} catch (Exception x) {
System.out.println(x.getMessage());
}
}
}
Run Code Online (Sandbox Code Playgroud)
如何在不必为BufferedReader等类创建包装器的情况下区分这些异常?
大多数情况下,我将资源关闭在finally块中的try/catch中,而不关心处理它.
AFAIK,标准try-with-resources形式
try(InputStream is= new ...){
... some reading from is
} catch (..){
... catching real problems
}
catch (IOException e) {
... if closing failed, do nothing - this clause is demanded by syntax
}
Run Code Online (Sandbox Code Playgroud)
相当于:
try{
InputStream is= new ...
... some reading from is
} catch (..){
... catching real problems
} finally {
try{
is.close();
} catch (IOException e) {
... if closing failed, do nothing
}
}
Run Code Online (Sandbox Code Playgroud)
当然,第一个变体更简单。但是我看到第二个变体绝对可以的情况,而第一个变体变得无法理解。
想象一下这种情况,当你得到代码时,try(){}出现在函数 withthrows …
每当我需要在Java中获取资源然后保证资源被释放时,可能会抛出异常,我使用以下模式:
try {
Resource resource = null;
try {
resource = new Resource();
// Use resource
} finally {
if (resource != null) {
// release resource
}
}
} catch (Exception ex) {
// handle exceptions thrown by the resource usage or closing
}
Run Code Online (Sandbox Code Playgroud)
例如,如果我需要数据库连接,并且使用或关闭连接可能会抛出异常,我会编写以下代码:
try {
Connection connection = null;
try {
connection = ... // Get database connection
// Use connection -- may throw exceptions
} finally {
if (connection != null) {
connection.close(); // This can …Run Code Online (Sandbox Code Playgroud)