[英]What exception to throw if JNDI datasource connection is null?
I have following code: 我有以下代码:
static Connection getConnection() {
String datasourceContext = "jdbc/infy";
Connection connection = null;
try {
Context initialContext = new InitialContext();
DataSource datasource = (DataSource) initialContext
.lookup(datasourceContext);
if (datasource != null) {
connection = datasource.getConnection();
connection.setAutoCommit(false);
} else {
System.out.println("Failed to lookup datasource");
}
} catch (NamingException e) {
System.out.println("Failed to get context " + e);
} catch (SQLException e) {
System.out.println("Failed to get connection " + e);
}
return connection;
}
I am trying to make neat and testable code, and my question is: how to correctly handle the case when the datasource is null, or/and connection is null, without using conditional statements. 我试图编写简洁且可测试的代码,而我的问题是:如何在不使用条件语句的情况下正确处理数据源为null或/和connection为null的情况。 I think the best thing to do is to throw an exception, but what kind of exception?
我认为最好的方法是引发异常,但是什么样的异常呢? Thank you.
谢谢。
JNDI lookup throws a NameNotFoundException if the datasource is not found. 如果未找到数据源,则JNDI查找将引发NameNotFoundException 。 AFAIK it should never return null, so I don't see the point in null check.
AFAIK它永远不会返回null,所以我在null检查中看不到该点。
You could tweak your error message about NamingException since currently it is misleading, NameNotFoundException is a NamingException as well - though what you really should do is to just rethrow the exception you're getting. 您可以调整有关NamingException的错误消息,因为当前它具有误导性,NameNotFoundException也是NamingException-尽管您真正应该做的只是重新抛出所获取的异常。 I would just change it to unchecked exception instead of checked, like
我只是将其更改为未经检查的异常,而不是经过检查的,例如
catch (NamingException e) {
throw new IllegalStateException("Failed with JNDI lookup of "
+ datasourceContext, e);
}
And in the similar way with SQLException. 并且以与SQLException类似的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.