异常,以及在重置连接时如何最好重试? [英] Exceptions, and how best to retry when a connection is reset?
问题描述
我有一些代码连接到一个URL下载一个文件,然后对其执行一些处理。但是,有时我收到错误 java.net.SocketException:Connection reset
。
I have some code which connects to a URL to download a file, and then performs some processing on it. However, sometimes I am receiving the error java.net.SocketException: Connection reset
.
下载文件时我收到这个错误,说最多3次后放弃就可以了。我想知道什么是最好的结构这个方法。
I would like to retry to download the file when I receive this error, say a maximum of 3 times before giving up on it. I would like to know what would be the best way to structure this.
执行以下操作。将 try-catch
块放在和
循环中似乎是可以接受的,还是有更好的方法?
Does the following look ok. Does it seem acceptable to place the try-catch
block inside of a while
loop, or is there a better approach?
所有帮助非常感谢!
while(!connected && retries > 0) {
retries--;
URL downloadUrl;
URLConnection conn;
try {
downloadUrl = new URL(url);
conn = downloadUrl.openConnection();
conn.connect();
connected = true;
// Perform processing on downloaded file here
} catch (IOException e) {
Logger.batchLog(e);
}
}
推荐答案
I已经有线认为吞咽异常总是坏,但我认为这是唯一的方法来告诉连接是否确实重置。我想你正在根据你的要求处理异常,所以这是所有的事情。
I've been wired to think that swallowing an exception is always bad, but I think here, that's the only way to tell if the connection was indeed reset. I guess you are handling the exception according to your requirements, so that's all the matters.
但是,我会,让它,所以你不要吞下最后一个异常。如果它失败了三次,你会想要重新抛出该异常或以某种方式失败。
But I would, however, make it so you don't swallow the last exception. If it fails three times, you'll want to rethrow that exception or fail gracefully somehow.
这篇关于异常,以及在重置连接时如何最好重试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!