首页 > 解决方案 > 我们可以从 finally 块进行递归调用吗?

问题描述

在下面的代码中,当我在增加超时参数后对 SocketTimeOutException 进行递归调用时,finally 块返回我空白“”,尽管它从服务器获得响应。

*private String getBuc2Responses(String ip, String uri, int timeoutAddition) throws IOException {
    HttpURLConnection connection = null;
    String line = "";
    successful_conn = true;
    boolean teminateByException = false;
    int timeout = 1000;
    try {
        URL url = new URL(ip+uri);
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setReadTimeout(1000);
        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        line = reader.readLine();               
        retry = 0;      

    } catch (ConnectException ex){
        successful_conn = false;
        retry++;
        ex.printStackTrace();
    } catch (SocketTimeoutException ex) {
        ex.printStackTrace();
        if(retry<=3){
        successful_conn = false;
        retry++;
        timeout += 1000;
        } else {
            teminateByException = true;
            throw new SocketTimeoutException(ex.toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
        teminateByException = true;
        throw new IOException(e);
    }finally{
        connection.disconnect();
        if(!teminateByException){
            if(!successful_conn && (retry>0 && retry<=3)){
                String ip1 = "http://"+mapIp.get(new Random().nextInt(mapIp.size())+1);
                getBuc2Responses(ip1, uri, timeout);
            } else{
                retry = 0;
                return line;
            }
        }                       
    }
    return line;
}*

在没有递归调用的情况下,finally 块的 else 部分返回正常,但是对于一次重试,它会发送空白字符串。我有两个全局变量定义如下:

***int retry = 0;
boolean successful_conn = true;***

谢谢,

标签: javaexception

解决方案


推荐阅读