异常后继续执行

时间:2013-04-18 12:57:45

标签: java exception loops

我有这两个类:

public class TryException {
    int a=0;

    TryException(int c) {
        a = c;
    }

    public boolean operation() //just example
    {
        if(a!=10)
        {
            System.out.println(a);
            return true;
        }else{
            throw new RuntimeException("display something");
        }

    }

}

和主要:

public class Test {
    static public void main(String args[])
    {
        int val =20;
        TryException ex = new TryException(val);

        try{
            while(ex.operation()){
                ex.a = --val;
            }

        }catch(RuntimeException e)
        {
            System.out.println("try exception");
        }
    }
}

当我运行这个程序时,执行会在检测到异常时停止。如何在异常后继续执行相同的while

2 个答案:

答案 0 :(得分:3)

这可能有帮助...

public class Test {
    static public void main(String args[])
    {
        int val =20;
        TryException ex = new TryException(val);

        boolean status = true;
        while(status){
            try{
                 status = ex.operation();
            } catch(RuntimeException e) {
                status = true; //Or whatever...
            }
            ex.a = --val;
        }
    }
}

答案 1 :(得分:3)

将try-catch移动到循环内。

 boolean run = true;
 while(run){
    ex.a = --val;
    try{
       run = ex.operation();
    }catch(RuntimeException e){
        System.out.println("try exception");
    }    
 }

您需要决定何时将run设置为false ...