Java7 try-with-resources语句优势 [英] Java7 try-with-resources Statement advantage
问题描述
我正在寻找Java7的新功能。我发现有一个是 try-with-resources声明。任何人都可以告诉我它究竟意味着什么?我们应该使用它的原因和位置,以及我们可以在哪里获得此功能的优势?即使是尝试
语句也会错过 catch
这个让我感到困惑的块。
它的引入是因为Java中使用的一些资源(如SQL连接或流)难以正确处理;例如,在java 6中正确处理 InputStream 你必须做类似的事情:
InputStream stream = new MyInputStream(...);
try {
// ...使用流
} catch(IOException e){
//处理异常
}最后{
try {
if(stream!= null){
stream.close();
}
} catch(IOException e){
//处理另一个可能的异常
}
}
你注意到丑陋的双重尝试吗?现在使用try-with-resources可以执行以下操作:
try(InputStream stream = new MyInputStream(...)){
$ p自动调用$ p>
// ...使用流
} catch(IOException e){
//处理异常
}
和 close(),如果它抛出IOException,它将被抑制(如 Java语言规范14.20.3 )。 java.sql.Connection
也是如此I was looking the new feature of Java7. I found one is try-with-resources Statement. Can anybody tell me what exactly it means? Why and where we should use it and where we can get advantage of this feature? Even the
try
statement missescatch
block which confusing for me.解决方案It was introduced because of some resources used in Java (like SQL connections or streams) being difficult to be handled properly; as an example, in java 6 to handle a InputStream properly you had to do something like:
InputStream stream = new MyInputStream(...); try { // ... use stream } catch(IOException e) { // handle exception } finally { try { if(stream != null) { stream.close(); } } catch(IOException e) { // handle yet another possible exception } }
Do you notice that ugly double try? now with try-with-resources you can do this:
try (InputStream stream = new MyInputStream(...)){ // ... use stream } catch(IOException e) { // handle exception }
and close() is automatically called, if it throws an IOException, it will be supressed (as specified in the Java Language Specification 14.20.3) . Same happens for java.sql.Connection
这篇关于Java7 try-with-resources语句优势的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!