java - 重复某件事直到成功,但最多 3 次
问题描述
自从编写 Java 以来,我需要多次编写这样的程序:
做一些可能失败的事情。如果失败,请再试一次,但最多 3(或 2 或 5)次。
这种方法应该有效:
for (int i = 0; i < 3; i++) {
try {
doSomething();
} catch(BadException e) {
continue;
}
break;
}
但我不认为它很有表现力。你有更好的解决方案吗?
像这样的东西会很好:
try (maxTimes = 3) {
doSomething();
} catch(BadException e) {
retry;
}
或者:
try (maxTimes = 3) {
doSomething();
if(somethingFailed()) {
retry;
}
}
但这对于 Java 是不可能的。你知道一种语言可以使用它吗?
解决方案
Java 不允许您发明自己的语法,但您可以定义自己的方法来帮助您用更少的代码表达概念:
public static boolean retry(int maxTries, Runnable r) {
int tries = 0;
while (tries != maxTries) {
try {
r.run();
return true;
} catch (Exception e) {
tries++;
}
}
return false;
}
现在你可以像这样调用这个方法:
boolean success = retry(5, () -> doSomething());
// Check success to see if the action succeeded
// If you do not care if the action is successful or not,
// ignore the returned value:
retry(5, () -> doSomethingElse());
推荐阅读
- html - 将 div 设为特定 div 的绝对值
- bash - 如何使用远程提交到使用 Loadleveler 的集群的作业的状态作为 BASH 脚本中的循环控制参数?
- python - 使用 ffmpeg_extract_subclip 提取视频的一部分 - 黑帧
- javascript - 条形图的工具提示在角度中使用 d3-tip?
- html - Firefox 不随机支持文本上的掩码图像
- sql-server - 每次自动递增列 1,2,3 SQL server
- android - 使用 RxJava 时如何重试对 HTTP 错误 (401) 的 Retrofit 调用?
- android - 无法添加任务“:app:reportSourceSetTransformTest”,因为具有该名称的任务已存在
- amazon-lex - 如何通过 .NET SDK 构建 aws lex bot
- php - 邮件未使用 godaddy 服务器发送-Smtp 未连接