I have a getMyProperties() method that pulls and returns various properties files and it handles the exception there. However, Eclipse says that another method getRequest() that calls getMyProperties() should also have "throws IOException". Even then after adding this, Eclipse says the main method which calls getRequest() should throw the exception as well. Is this the correct way to handle exceptions? Something about it seems wrong.
After doing what Eclipse suggests, I have the following in my main method. It shows no errors, but is it correct?
public static void main(String[] args) throws IOException {
//some code...
myRequest = TestApiCall.getRequest(type, sQuery);
//some more code...
}
Here are the methods in a separate 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;
}
Here is the method after the changes, as suggested by Jocelyn and Vasquez. Hopefully looking much better!
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)
should not throw IOException
since you are catching Exception
here. Hence getRequest()
has no need to declare it and your problem is solved.
Nevertheless, I advise you to never catch Exception
as a whole, you should only catch IOException
and FileNotFoundException
here.