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

Que*_*eff 0 java methods recursion return

这是我的问题:

我必须连接到代理服务(这里是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;
}
Run Code Online (Sandbox Code Playgroud)

在getConnection()方法中,如果我捕获SocketTimeOutException,我会使用另一个url进行递归调用.这是工作,但第一个调用在第二个之前返回null,我在connection.createSession(...)上得到一个NPE;

我不知道我能做些什么来解决它?

Bri*_*new 5

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

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
Run Code Online (Sandbox Code Playgroud)

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

上面将连接(和错误处理)的连接与重试机制隔离开来,可以说它更简单,更易于理解.