如何从 try-with-resources 中捕获异常? [英] How to catch exceptions from try-with-resources?

查看:38
本文介绍了如何从 try-with-resources 中捕获异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尽管 try-with-resources 功能本身可以处理 AutoClosable 对象的所有功能,但我在最近的项目中遇到了一些特定情况.

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"))

问题是我读取上述文件的路径错误.因此,我预计会出现FileNotFoundException"异常.现在,我知道当我使用 try-with-resources 时,我可以在适当的位置设置 catch 块,而不是在适当的位置.此外,令我惊讶的是,我的 catch 块没有捕获任何异常,日志中也没有出现任何错误.

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.

如果不需要那个带有 try-with-resources 的 catch 块,那为什么要在那里添加它呢?而且,当它不存在时,是否会抛出任何异常?在第二种情况下是否向 JVM 抛出了异常,我该如何记录这些异常?

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?

下面是我的代码:

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

推荐答案

getResourceAsStream(name) 可能抛出的唯一异常是 NullPointerExceptioncode>name 为 null.即使找不到资源也不会抛出任何其他异常.

The only exception getResourceAsStream(name) could throw is a NullPointerException and that too, when the name is null. It will not throw any other exception even if the resource is not found.

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

If you want your code to throw a FileNotFoundException when resource is missing, then use new FileInputStream(String resourceName) (which throws the required file not found exception) to load your resource instead of getResourceAsStream()

这篇关于如何从 try-with-resources 中捕获异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆