java如何退出所有递归

来源:互联网 发布:猪八戒淘宝直播 编辑:程序博客网 时间:2024/06/16 06:54
以异常形式抛出,抛出后执行catch内的语句,与递归本身返回值无关


public class Main {
    public static void main(String args[]) {
        System.out.println("start!");
        try {
            find(0);
        catch (StopMsgException 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 0