当方法中出现异常时,我尝试重新执行指定次数的方法,但无法重新执行该方法。
int maxretries=10;
void show(){
try{
display();
}
catch(Exception e)
{
for(int i=1;i<maxretries;i++){
display();//on first retry only I am getting exception
}
}
}
当我运行代码时,它是为第一次重试执行的,并且我得到了异常,但是我希望重新执行display()
方法,直到它被成功地执行,并在最大重试中成功地执行。
发布于 2016-05-12 10:47:56
在catch中编码的调用不是在try中,所以它不会捕获异常。
为此,您需要使用其他概念,或者再次调用整个函数,或者在catch内部编写一个连续的try块(在catch块中进一步编写try块,等等),或者围绕整个try块编写循环代码(可能是最好的方法)。
发布于 2016-05-12 10:56:25
那这个呢?
int maxretries = 10;
for (int i = 0; i < maxretries; i++) {
try {
display();
break;
} catch (Exception e) {
// log exception
e.printStackTrace();
}
}
发布于 2016-05-12 11:35:17
在下面的程序中,我正在执行指定次数的重新运行方法,即使出现异常的时间间隔为5秒。
public class ReExecuteMethod {
public static void main(String[] args) throws Exception {
int count = 0;
while (count <= 10) {
try {
rerun();
break;
} catch (NullPointerException e) {
Thread.sleep(5000);
System.out.println(count);
count++;
}
}
System.out.println("Out of the while");
}
static void rerun() {
// throw new NullPointerException();
System.out.println("Hello");
}
}
https://stackoverflow.com/questions/37184583
复制相似问题