虽然 try-with-resources 功能可以处理 AutoClosable 对象本身的所有功能,但我在最近的项目中遇到了一些特定情况。
我正在使用以下方式读取文件:
尝试(InputStream流= loader.getResourceAsStream(“remote-config.xml”))
问题是我读取上面文件的路径是错误的。因此,我预计会出现“FileNotFoundException”异常。现在,我知道当我使用 try-with-resources 时,我可以将 catch block 放在适当的位置,也可以不将其放在适当的位置。另外,令我惊讶的是,我的 catch block 没有捕获任何异常,并且我的日志中没有收到任何错误。
如果不需要带有 try-with-resources 的 catch block ,那么为什么要在那里添加它呢?而且,当它不存在时,是否会抛出任何异常?第二种情况是否会向 JVM 抛出异常?我该如何记录这些异常?
下面是我的代码:
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;
}
最佳答案
唯一的异常(exception)getResourceAsStream(name)
可以抛出的是 NullPointerException
也是如此,当 name
是 null
。即使找不到资源,也不会抛出任何其他异常。
如果您希望代码抛出 FileNotFoundException
当资源丢失时,则使用 new FileInputStream(String resourceName)
(抛出所需的文件未找到异常)来加载您的资源而不是 getResourceAsStream()
关于java - 如何从 try-with-resources 捕获异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67396600/