为什么下面这段代码不合法??       class ExceptionA extends Exception {}
        class ExceptionB extends ExceptionA {}
        public class Test{
            void thrower() throws ExceptionA{
             throw new ExceptionA();
            }
            public static void main(String[] args){
               Test t = new Test();
               try{t.thrower();}
               catch(ExceptionB e) {}
            }
          }

解决方案 »

  1.   


     try {
                t.thrower();
            } catch (ExceptionB e) {
            } catch (ExceptionA e) {
            }因为还要catch ExceptionA e
      

  2.   

    而且ExceptionA 一定要在 ExceptionB的下面捕获,因为是ExceptionA 是ExceptionB的父类
    飞过~~
      

  3.   

    package com.question;public class Q10 {    void thrower() throws ExceptionA {
            throw new ExceptionB();
        }
        
        public static void main(String[] args) {
            Q10 q10 = new Q10();
            try {
                q10.thrower();
            } catch (ExceptionA e) {
                e.printStackTrace();
            }
        }
        
        public class ExceptionA extends Exception {
            
        }
        
        public class ExceptionB extends ExceptionA {
            
        }
    }
    换成这样试试
    LZ在thrower()方法中抛出的异常为ExceptionA,  在main方法里没有捕获, 所以就出错误了 
      

  4.   

    package com.question;public class Q10 {    void thrower() throws ExceptionB {
            throw new ExceptionB();
        }
        
        public static void main(String[] args) {
            Q10 q10 = new Q10();
            try {
                q10.thrower();
            } catch (ExceptionB e) {
                e.printStackTrace();
            }
        }
        
        public class ExceptionA extends Exception {
            
        }
        
        public class ExceptionB extends ExceptionA {
            
        }
    }
      

  5.   

    class ExceptionA extends Exception {} 
    class ExceptionB extends ExceptionA {} 
    public class Test{ 
        void thrower() throws ExceptionA{ 
        throw new ExceptionA(); 
        } 
        public static void main(String[] args) throws ExceptionB{ 
          Test t = new Test(); 
          try {
    t.thrower();
    } catch (ExceptionA e) {
    // TODO Auto-generated catch block
    e.printStackTrace();

        } 
      }
      

  6.   


    class ExceptionA extends Exception {}
            class ExceptionB extends ExceptionA {}
            
            public class Test{
                void thrower() throws ExceptionA{
                throw new ExceptionA();
                }
                public static void main(String[] args){
                  Test t = new Test();
                  try{t.thrower();}
    /*catch只能捕获ExceptionA或Exception,不能捕获ExceptionA的子类ExceptionB,因为thrower()抛出的异常是ExceptionA*/
                  catch(ExceptionA e) {}   
                }
              }
      

  7.   

    抛的是父类
    不能用子类去接收Exception啊