1

我有这两个类:

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

4

2 回答 2

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;
        }
    }
}
于 2013-04-18T13:02:28.020 回答
3

将 try-catch 移动到循环内。

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

您需要决定何时设置runfalse...

于 2013-04-18T13:02:32.223 回答