-3

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();
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • 1
    https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html – takendarkk Oct 09 '20 at 15:03
  • 1
    These aren't equivalent code blocks, so your question makes no sense. In the first block, `httpClient.close()` will be called when the code exits the `try/catch` block. That's the whole point of `try(statement)`. - as the documentation referenced above describes. – CryptoFool Oct 09 '20 at 15:05
  • See https://stackoverflow.com/q/17739362/217324 – Nathan Hughes Oct 09 '20 at 15:17

1 Answers1

1

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.

Piyush N
  • 742
  • 6
  • 12