Skip to content
Advertisement

spring try catch vs try(statement) catch – spring

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();
}

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement