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 块放在 while 循环内似乎可以接受,还是有更好的方法?
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'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.
但是,我会这样做,以免您吞下最后一个例外.如果它失败了 3 次,您将需要重新抛出该异常或以某种方式优雅地失败.
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.
这篇关于异常,以及在连接重置时如何最好地重试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:异常,以及在连接重置时如何最好地重试?
基础教程推荐
- Maven:无效的目标版本:10 2022-01-01
- JPA惰性列表上的流 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 在springboot中如何给mybatis加拦截器 2023-04-29
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
