java问题,求大神解答

假如有个方法getId()可能会抛异常,我try catch 包住,然后再for循环30次,每隔5秒执行一次,直到这个方法不抛异常就退出循环,请问代码应该怎样写呢?

这样应该可行。

代码截图

代码如下:

public class Test {

public static void main(String[] args) throws InterruptedException {
for (int i = 0; i < 30; i++) {
try{
getId();
System.out.println("没有异常,结束运行");
break;//没有异常就退出循环
}catch (Exception e){
System.out.println("异常:"+e.getMessage());
Thread.sleep(5000);//抛出异常就睡眠5秒,再继续循环
}
}
}

/**
* 模拟的可能会抛出异常的方法。
*/
public static void getId() throws Exception {
double random = Math.random();
if (random>0.2){
throw new Exception("random="+random);
}
}
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2020-03-10
你try和catch后,对异常不做处理或直接sysout输出异常信息,保证线程不被阻断,能正常执行,最外面包一个for循环就行了,加个标志符,默认是true,在catch里面设置为false,在异常外设置true,加入for循环条件中,避免执行成功后还循环执行
相似回答