在 catch 块方法中递归调用 who return 值

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 进行递归调用。这是可行的,但是第一次调用 return 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的meaning/handling

以上将连接的建立(和错误处理)与重试机制隔离开来,可以说它更简单、更容易理解。