【发布时间】:2021-07-27 11:57:48
【问题描述】:
虽然 try-with-resources 功能处理了 AutoClosable 对象本身的所有功能,但我在最近的项目中遇到了一些特定情况。
我正在使用以下方式读取文件:
try(InputStream stream = loader.getResourceAsStream("remote-config.xml"))
问题是我读取上述文件的路径错误。所以,我预计会有一个异常为“FileNotFoundException”。现在,我知道当我使用 try-with-resources 时,我可以设置 catch 块,但也可以不设置它。此外,令我惊讶的是,我的 catch 块没有捕获任何异常,并且我的日志中没有任何错误。
如果不需要带有 try-with-resources 的 catch 块,那么为什么可以将它添加到那里?而且,当它不存在时,是否会抛出任何异常?在第二种情况下是否会向 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;
}
【问题讨论】:
-
有点,但它具体指的是 Autoclosable 对象上的关闭异常,而不是 FileNotFoundException 之类的特定异常。无论如何,谢谢你。我也会看看。只有当我无法捕捉到异常时我才知道这一点,这让我发疯了。我不得不做很多烦人的体力工作。
-
你确定
FileNotFoundException被抛出了吗?因为catch子句会捕获异常,即使它不是由于close()。 -
我在 Wildfly 上部署了应用程序。最初,我尝试更改日志记录级别,认为它没有因此而被记录但没有结果。所以,我也尝试了 syso/sout。但是,一无所获。不确定它是否会像它一样工作。或者我错过了一些东西,但是我粘贴的代码是我唯一错误的,try 块中的其余实现什么都没有。即使它没有打印我放在 try 中的第一个 print 语句,说它没有进入 try。
标签: java try-catch java-7 try-with-resources