繁体   English   中英

异常后继续执行

[英]Continue the execution after exception

我有这两个类:

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异常后?

这可能会帮助...

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;
        }
    }
}

在循环内移动try-catch。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM