try {
    methodA();
} catch (Exception e) {
    
}
    这个try catch块放在main()函数中,一旦methodA()抛出了异常,程序就会终止,我希望当程序抛出异常时候,程序能够自动再去执行一遍methodA(),直到methodA()正常结束为止。请问有什么好办法吗?

解决方案 »

  1.   

    这个异常是没办法的,有的时候他就是要抛出异常。比如我的应用里面,methodA()是一个从远程获取XML片断并进行解析的方法,但是不能保每次远程获取的时候都成功,不成功的时候就是要抛出异常,如果想要保持程序的连贯性,就不得不出现一次异常就手动重新启动程序。我这么问肯定是有我的道理的。如果能事先解决,我就不问了,呵呵。
      

  2.   


    boolean b = true;
    while(b) {
      try {
    methodA();
            b = false;
      } catch (Exception e) {    continue;
      }
    }不知道这样行不行
      

  3.   

    借用3楼同学的思路。import java.util.Random;
    public class Test {   
        public int randomMethod() throws Exception{
            Random r = new Random();
            int i = r.nextInt(10);
            if(i<=5) // 不大于5就抛异常
                throw new Exception("随机数小了点!" + i);
            return i;
        }    public void doSomething() {
            int i = 0;
            while (true) {
                try {
                    i = randomMethod();
                    break;
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }
            System.out.println("i = " + i);
        }    public static void main(String[] args) throws Exception {
            new Test().doSomething();
        }
    }
      

  4.   

    methodB(){
     try { 
        methodA(); 
     }catch(Exception e) { 
        methodB()
     } 
    }