假如有个方法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);
}
}
}