我尝试在方法中发生异常时重新执行指定次数的方法, 但我无法重新执行方法
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()
方法,直到最大限度重试它才能成功执行。
答案 0 :(得分:3)
您在catch中编码的调用不在try中,因此它不会捕获异常。
你需要使用其他概念来做到这一点,要么再次调用整个函数,要么在catch中编写一个连续的try块(以及catch块内的另一个try块等),或者编写循环整个尝试块(可能是最好的方法)。
答案 1 :(得分:2)
这个怎么样:
int maxretries = 10;
for (int i = 0; i < maxretries; i++) {
try {
display();
break;
} catch (Exception e) {
// log exception
e.printStackTrace();
}
}
答案 2 :(得分:0)
在下面的程序中,我正在执行指定次数的重新运行方法,即使发生了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");
}
}