public class Reluctant {    private Reluctant internalInstance = new Reluctant();
    
    public Reluctant() throws Exception {
        throw new Exception("I'm not coming out");
    }  
    public static void main(String[] args) {  
        try {
            Reluctant b = new Reluctant();
            System.out.println("Surprise!");
        } catch (Exception ex) {
            System.out.println("I told you so");
        }
    }
}

解决方案 »

  1.   

    这不是一个死循环么?无限throw!!
      

  2.   

    因为你在该类内部又创建了一个该类的私有成员,并且你的Exception是从构造函数处抛出的。public class Reluctant {    private Reluctant internalInstance = new Reluctant(); // 这个地方会抛出异常。并且会死循环似得不停的创建子对象。例如:internalInstance.internalInstance.internalInstance.internalInstance......
        
        public Reluctant() throws Exception {
            throw new Exception("I'm not coming out");
        }  
        public static void main(String[] args) {  
            try {
                Reluctant b = new Reluctant();
                System.out.println("Surprise!");
            } catch (Exception ex) {
                System.out.println("I told you so");
            }
        }
    }
      

  3.   

    本身你这样定义类就是不对的。子对象创建递归了。我想你是想要下面的结果:
    public class Reluctant {    private static Reluctant internalInstance = new Reluctant(); // 使用static定义类变量
        
        public Reluctant() throws Exception {
            throw new Exception("I'm not coming out");
        }  
        public static void main(String[] args) {  
            try {
                Reluctant b = new Reluctant();
                System.out.println("Surprise!");
            } catch (Exception ex) {
                System.out.println("I told you so");
            }
        }
    }