将属性从一种方法传回另一种方法时如何处理异常

How do I handle exceptions when passing properties back from one method to another

我有一个 getMyProperties() 方法可以提取和 returns 各种属性文件,它可以处理那里的异常。然而,Eclipse 说另一个调用 getMyProperties() 的方法 getRequest() 也应该有 "throws IOException"。即使在添加这个之后,Eclipse 说调用 getRequest() 的主要方法也应该抛出异常。这是处理异常的正确方法吗?好像有点不对。

按照 Eclipse 的建议进行操作后,我的主要方法中有以下内容。它没有显示任何错误,但它是否正确?

public static void main(String[] args) throws IOException {
        //some code...
        myRequest = TestApiCall.getRequest(type, sQuery);
        //some more code...     
    }

下面是单独的方法 class...

static String getRequest(String rType, String query) throws IOException{
        Properties myProps = null;
        String request = "";
        switch (rType){
            case "XML-SBQ":
                request = CallConsts.XML_SBQ_CALL;
                myProps = getMyProperties("configSBQ.properties");
                //use the properties
                break;
            case "JSON-SBQ":
                request = CallConsts.JSON_SBQ_CALL;
                //use the properties
                break;
            case "JSON-gos":
                request = CallConsts.JSON_GOS_CALL;
                myProps = getMyProperties("configGOS.properties");
                //use the properties
        }
        return request;
    }

    static Properties getMyProperties(String propName) throws IOException{
        Properties prop = new Properties();
        InputStream inputStream = null;

        try {
            String propFileName = propName;

            inputStream = TestApiCall.class.getClassLoader().getResourceAsStream(propFileName);

            if (inputStream != null) {
                prop.load(inputStream);
            } else {
                throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
            }
        } catch (Exception e) {
            System.out.println("Exception: " + e);
        } finally {
            inputStream.close();
        }
        return prop;

    }

这是更改后的方法,按照 Jocelyn 和 Vasquez 的建议。希望看起来好多了!

static Properties getMyProperties(String propName) {
    Properties prop = new Properties();
    String propFileName = propName;

    try (InputStream inputStream = TestApiCall.class.getClassLoader().getResourceAsStream(propFileName)){

        if (inputStream != null) {
            prop.load(inputStream);
        } else {
            throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
        }
    } catch (IOException e) {
        System.out.println("Exception: " + e);
    } 
    return prop;
}

getMyProperties(String propName) 不应该抛出 IOException 因为你在这里捕获 Exception。因此 getRequest() 不需要声明它,你的问题就解决了。

不过,我建议你永远不要把 Exception 作为一个整体来抓,你应该只抓这里的 IOExceptionFileNotFoundException