java怎么退出所有递归?

其中一个函数,return只能退出一层,我想一下子退出所有递归,网上说用抛出异常,但我不知怎么做?设置标志位我试过了不行。求大神!

public class Main {
public static void main(String args[]) {
System.out.println("start!");
try {
find(0);
} catch (StopMsgException e) {
System.out.println(e);
}
System.out.println("done!");
}

private static void find(int level) {

if (level > 10) {
// 跳出
throw new StopMsgException();
}
// 执行操作
System.out.println(level);
// 递归
find(level + 1);
}

static class StopMsgException extends RuntimeException {
}
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-04-15
比如这是一个递归:
public int a(int p){
...

p--;

a(p);

...

}

那么我想要退出递归时:
public int a(int p){
...

if(p == 0){

throw new Exception("blahblah"); //抛出异常

}

p--;

a(p);

...

}
调用这个递归时:
public static void main(String[] args){
try{
a(2);

}catch(Exception e){
//抛出异常后执行

}

}
简单来说就是抛出异常后会执行catch内的语句,与递归本身的返回值无关。本回答被网友采纳
相似回答