I have a great number of methods for a class that require catching some checked exceptions, where they will all be handled the same way. Hence, I want to write a method to enclose all of the functions with the try catch. Here is the full code, using JDBC:
private static <T> T HandleResultSet(ResultSet rs, Function<ResultSet, T> fn) {
T returnValue = null;
try {
while (rs.next()) {
returnValue = fn.apply(rs);
}
}
catch(SQLException se)
{
se.printStackTrace();
}
finally
{
try {
if (rs != null)
rs.close();
}
catch(SQLException se) {
se.printStackTrace();
}
return returnValue;
}
}
public static String MySQLMethod(int param)
{
Function<ResultSet, String> getProperty = (ResultSet set) ->
{
if (set.next())
return set.getString("Property");
return "ERR";
};
ResultSet rs = CallSQL("SELECT * FROM [User] WHERE Param = '" + param + "';");
return HandleResultSet(rs, getProperty);
}
For those unfamiliar with JDBC, the important part is that the methods "set.next()" and "set.getString()" in my "getProperty" function require a catch on SQLException. This catch is included in "HandleResultSet", but the compiler doesn't seem smart enough to know that, and I can't seem to get around the issue. Any thoughts on ways to handle this?
I am using the latest version of IntelliJ IDEA.
If you look at signature of java.util.function.Function#apply
it doesn't throw any exception. So you have to create your own interface which throws SQLException
:
@FunctionalInterface
public interface CheckedFunction<T, R> {
R apply(T t) throws SQLException;
}
and then:
CheckedFunction<ResultSet, String> getProperty = (ResultSet set) -> {
if (set.next())
return set.getString("Property");
return "ERR";
};
Also use try-with-resources
for ResultSet