英文:
spring try catch vs try(statement) catch - spring
问题
我想知道在Spring中我看到的**try(statement?){} catch()和try{} catch()**之间的区别(如果有的话),以及在.net中是否也正确。我已经尝试过两者,但没有看到任何区别。这是为了性能还是仅仅是选择?
示例:
try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build()) {
log.warn("closeable call");
// 一些逻辑
}
catch (Exception e) {
e.printStackTrace();
}
try {
// 一些逻辑
} catch (Exception e) {
e.printStackTrace();
}
英文:
I wanted to know the difference (if any) between try(statement?){} catch() and try{} catch(), that I saw applied in Spring, and if I'm also correct in .net. I have tried both but have not seen any difference. Is it for performance or just a choice?
example:
try (CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build()) {
log.warn("closeable call");
// some logic
}
catch (exception e) {
e.printStackTrace();
}
try {
// some logic
} catch (exception e) {
e.printStackTrace();
}
答案1
得分: 1
只是想在回答你的问题之前提到两件事情。
- try(statement) 不是 Spring 的特性。它是 Java 的特性,引入自 Java 7。
- try(statements) 被称为 try with resources。
关于 try(statements):
try 内部的语句可以是任何直接或间接实现/扩展 Java 中的 AutoCloseable 接口的类或接口引用。(AutoCloseable 接口具有抽象方法 close())。这意味着您无需显式调用资源的 close() 方法。如果您不使用带资源的 try,程序员必须显式调用已打开资源的 close() 方法。
有关更多详细信息,请阅读有关 Java 中的 try with resources。
英文:
Just wanted to mention two things before answering your question.
- try(statement) is not a spring feature. It is feature of Java which is introduced in Java-7.
- try(statements) is called as try with resources.
About try(statements):
Statement'(s) inside try can be any class or interface reference which directly or indirectly implement/extend AutoCloseable interface in java. (AutoCloseable interface have abstract method close()). Means you no need to call close() method explicitly for your resources. If you don't use try with resources programmer have to call close() method for opened resources explicitly.
For more detail read about try with resources in java.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论