繁体   English   中英

在catch块方法中递归调用谁返回值

[英]Recursive call in catch block method who return value

这是我的问题:

我必须连接到代理服务(此处为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;
}

在getConnection()方法中,如果捕获到SocketTimeOutException,则使用另一个URL进行递归调用。 可以,但是第一个调用在第二个调用之前返回null,并且我在connection.createSession(...)上得到了NPE。

我不知道该怎么办?

我不会通过递归来解决此问题,因为从直觉上看这并不是需要递归的问题。 我宁愿配置有效主机列表,并按顺序尝试它们,例如

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

并且在失败的情况下始终抛出异常,而不是混淆异常和null的含义/处理。

以上将连接的建立(和错误处理)与重试机制隔离开来,并且可以说使连接更加简单易懂。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM