我有这两个类:
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
?
最佳答案
将 try-catch 移到循环内。
boolean run = true;
while(run){
ex.a = --val;
try{
run = ex.operation();
}catch(RuntimeException e){
System.out.println("try exception");
}
}
您需要决定何时将 run
设置为 false
...
关于java - 异常后继续执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16083604/