黑马程序员技术交流社区
标题:
关于异常的问题
[打印本页]
作者:
kj1989
时间:
2013-12-28 15:11
标题:
关于异常的问题
本帖最后由 kj1989 于 2013-12-29 15:26 编辑
为什么在一个方法被覆盖时,覆盖它的方法必须扔出相同的异常或异常的子类呢?哪位高手能给个解释?
作者:
胡永城
时间:
2013-12-28 16:41
本帖最后由 胡永城 于 2013-12-28 16:42 编辑
1、覆盖的方法的标志符必须要和被覆盖的方法的标志符完全匹配,才能达到覆盖的效果;
2、覆盖的方法的返回值必须和被覆盖的方法的返回一致;
3、覆盖的方法所抛出的异常必须和被覆盖方法的所抛出的异常一致,或者是其子类;
4、被覆盖的方法不能为private,否则在其子类中只是新定义了一个方法,并没有对其进行覆盖。
覆盖呀,只有方法声明完全一致才可以称之为覆盖。抛出异常也是声明的一部分
作者:
天天学习
时间:
2013-12-28 19:55
原因:早期程序只能处理早期异常,不能处理后期产生的异常,以下以程序说明
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);
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2