[英]Recursive call in catch block method who return value
This is my problem : 这是我的问题:
I have to get a connection to a broker service (here activemq), so I do that : 我必须连接到代理服务(此处为activemq),因此我可以这样做:
public GenericMessageManager(String url, String producerQueue,
String consumerQueue) {
Connection connection;
try {
connection = getConnection(url);
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
producer = createProducer(producerQueue);
consumer = createConsumer(consumerQueue);
connection.start();
logger.info("Connection to broker started");
} catch (JMSException e) {
}
}
private Connection getConnection(String url) {
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
url);
try {
Connection connection = connectionFactory.createConnection();
return connection;
} catch (JMSException e) {
if (e.getLinkedException() instanceof SocketTimeoutException) {
logger.warn(url + " not responding, try on localhost");
getConnection("tcp://127.0.0.1:61616");
}
}
return null;
}
In the getConnection() method I do a recursive call with another url if I catch a SocketTimeOutException. 在getConnection()方法中,如果捕获到SocketTimeOutException,则使用另一个URL进行递归调用。 That's work but the first call return null before the second and I get a NPE on connection.createSession(...);
可以,但是第一个调用在第二个调用之前返回null,并且我在connection.createSession(...)上得到了NPE。
I don't know what can I do to solve it ? 我不知道该怎么办?
I wouldn't solve this via recursion, since it doesn't seem intuitively to be a problem requiring recursion as such. 我不会通过递归来解决此问题,因为从直觉上看这并不是需要递归的问题。 I would rather configure a list of valid hosts, and try them in order eg
我宁愿配置有效主机列表,并按顺序尝试它们,例如
for (String host : hosts) {
try {
Connection c = getConnection(host);
if (c != null) {
return c;
}
// log here (not sure I'd return null at all, mind)
}
catch (Exception e) {
// log here...
}
}
// fail completely
and consistently throw an exception in the case of failure, rather than confuse the meaning/handling of exceptions and nulls. 并且在失败的情况下始终抛出异常,而不是混淆异常和null的含义/处理。
The above isolates the making of the connection (and error handling) from the retry mechanism, and arguably makes it simpler and more comprehensible. 以上将连接的建立(和错误处理)与重试机制隔离开来,并且可以说使连接更加简单易懂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.