Though the try-with-resources feature handles all the functionalities for AutoClosable objects itself, but there are some specific cases I have faced in my recent project.
I was reading a file using:
try(InputStream stream = loader.getResourceAsStream("remote-config.xml"))
The issue was that the path from where I am reading the file above was wrong. So, I expected an exception as 'FileNotFoundException'. Now, I know that I can have catch block in place and not have it in place as well when I am using try-with-resources. Also, to my surprise, the catch block I had did not catch any exception and I did not get any error in my logs.
If there is no need of that catch block with try-with-resources, then why can it be added there? And, when it is not there, are there any exceptions thrown? Are the exceptions thrown to the JVM in the second case and how can I log those?
Below is the code I have:
private Map<String, String> fillMappingsMap(Map<String, String> serviceToJndiNameMappings)
{
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try(InputStream stream = loader.getResourceAsStream("remoting-config.xml"))
{
if (stream != null)
{
// logic for - read the file , fill the map to be returned.
}
}
catch (IOException | ParserConfigurationException | SAXException e)
{
logger.error("Could not create service to JNDI Name mapping.", e);
}
return serviceToJndiNameMappings;
}