java - 如何从 try-with-resources 捕获异常?

标签 java try-catch java-7 try-with-resources

虽然 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也是如此,当 namenull 。即使找不到资源,也不会抛出任何其他异常。

如果您希望代码抛出 FileNotFoundException当资源丢失时,则使用 new FileInputStream(String resourceName) (抛出所需的文件未找到异常)来加载您的资源而不是 getResourceAsStream()

关于java - 如何从 try-with-resources 捕获异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67396600/

相关文章:

java - 如果用户输入某个关键字并显示它,如何使 editText 获取 stringarray 的值?

c# - 在 .NET 中,try/catch 只是重新抛出 catch 有什么好处

java - JVM如何设置PATH环境变量

java - 在编译时使用 Java 7 u21,在运行时使用 Java 7 u13

java - HQL - 两个相同的查询 - 对象类型的差异

java - 从 REST GET 服务调用中获取整个查询字符串

java - 使用返回 400 状态代码的 Rest Assured Get 类型测试 REST API

java - 为什么我收到错误消息 "unreported exception Java.io in a java code when trying to read from a text file"?

c++ - throw关键字的使用

java - JDK7半透明+jframe+jcombobox