java - 我们可以从 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;***
谢谢,
解决方案
推荐阅读
- opencv - 使用 GrabCut 去除琐碎的背景
- c# - 从另一个类(委托)更新 WPF MainWindow 中的 ProgressBar
- c# - 如何将 MenuContextItem 的命令单击从一个用户控件绑定到 WPF 中的其他控件
- rabbitmq - 生产者和消费者没有解耦
- javascript - Javascript 的文档 lint
- android - 如何在 android 片段中使用 SQLite?
- reactjs - 如何根据由 react-helmet 动态更改的 html lang 使用大写
- javascript - 无法使用
节点作为对象上的翻译字符串 - modelica - 方程的实例化
- html - 如何将文本移动到页面右侧?