spring try catch与try(statement) catch – spring

huangapple go评论97阅读模式
英文:

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

只是想在回答你的问题之前提到两件事情。

  1. try(statement) 不是 Spring 的特性。它是 Java 的特性,引入自 Java 7。
  2. 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.

  1. try(statement) is not a spring feature. It is feature of Java which is introduced in Java-7.
  2. 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.

huangapple
  • 本文由 发表于 2020年10月9日 23:01:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/64282577.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定