原因:早期程序只能处理早期异常,不能处理后期产生的异常,以下以程序说明
1,父类抛出FuException,子类也抛出FuException
当otherMethod(Fu f)调用exceptonMethod()时根据多态原理,运行子类的exceptonMethod方法,并抛出FuException异常,此时方法的catch为catch (FuException e)因此可以处理这个异常,打印“出错了”,
- class FuException extends Exception
- {
- FuException(String message)
- {
- super(message);
- }
- }
- class ZiException extends Exception
- {
- ZiException(String message)
- {
- super(message);
- }
- }
- class Fu
- {
- public void exceptonMethod()throws FuException
- {
- throw new FuException("父类异常");
- }
- }
- class Zi extends Fu
- {
- public void exceptonMethod()throws FuException
- {
- throw new FuException("子类异常");
- }
- }
- class Other
- {
- public void otherMethod(Fu f)
- {
- try
- {
- f.exceptonMethod();
- }
- catch (FuException e)
- {
- System.out.println("出错了");
- }
- }
- }
- class MyTest
- {
- public static void main(String[] args)
- {
- Zi z = new Zi();
- Other o = new Other();
- o.otherMethod(z);
-
- }
- }
复制代码
2,父类抛出FuException,子类抛出ZiException
当otherMethod(Fu f)调用exceptonMethod()时根据多态原理,运行子类的exceptonMethod方法,并抛出ZiException异常,此时方法的catch为catch (FuException e)因此不可以处理这个异常导致程序无法进行
- class FuException extends Exception
- {
- FuException(String message)
- {
- super(message);
- }
- }
- class ZiException extends Exception
- {
- ZiException(String message)
- {
- super(message);
- }
- }
- class Fu
- {
- public void exceptonMethod()throws FuException
- {
- throw new FuException("父类异常");
- }
- }
- class Zi extends Fu
- {
- public void exceptonMethod()throws ZiException
- {
- throw new ZiException("子类异常");
- }
- }
- class Other
- {
- public void otherMethod(Fu f)
- {
- try
- {
- f.exceptonMethod();
- }
- catch (FuException e)
- {
- System.out.println("出错了");
- }
- }
- }
- class MyTest
- {
- public static void main(String[] args)
- {
- Zi z = new Zi();
- Other o = new Other();
- o.otherMethod(z);
-
- }
- }
复制代码 |