见下方示例代码:
-
import java.io.*;
-
-
public
class Father {
-
public void father_function() throws IOException {
-
new File(
"a.txt");
-
}
-
}
-
-
class Son extends Father {
-
@Override
-
public void father_function() throws Exception {
-
new File(
"b.txt");
-
}
-
}
-
-
class Test {
-
public static void main(String[] args) {
-
Father fs =
new Son();
-
try {
-
fs.father_function();
-
}
catch (IOException ie) {
-
System.out.println(
"发生了异常");
-
}
-
}
-
}
代码说明:
- 定义了一个类,类名为Father,Father中包含一个普通实例方法,但是该方法会抛出IOException
- 定义了一个Father类的子类:Son,该类重写了父类Father的方法,但是子类重写方法后选择了抛出一个更大的异常
- 定义了一个Test类,包含一个main方法
- Test类中创建了一个Son类对象(也即Father类的子类对象),然后使用try...catch...语句将fs.father_function();这条会抛出异常的语句包围,并使用了IOException对象对当前可能产生的异常进行捕
结果:
程序编译失败
原因分析:
1、在java多态机制中,对象引用fs在编译时期是属于父类类型也即Father类型,但是在运行时fs属于子类类型,也就是Son类型
2、也就是说在编译的时候,编译器发现catch中的IOException完全能将父类方法中抛出的异常捕获,因此编译通过,但是在运 行时期,由于fs变成了子类类型,子类重写的方法抛出的异常是Exception,显然IOException不能捕获这个比它更大的异 常,因此在运行时期也就出现失败
总结:这个示例也就演示了一个道理,在java中,子类重写父类的方法时,子类如果选择抛出异常,那么抛出的异常类型不能大于父类的异常类型
<div class="person-messagebox">
<div class="left-message"><a href="https://blog.csdn.net/xichengfengyulou">
<img src="https://profile.csdnimg.cn/0/1/F/3_xichengfengyulou" class="avatar_pic" username="xichengfengyulou">
</a></div>
<div class="middle-message">
<div class="title"><span class="tit "><a href="https://blog.csdn.net/xichengfengyulou" data-report-click="{"mod":"popu_379","ab":"new"}" target="_blank">西城风雨楼</a></span>
<!-- 等级,level -->
<img class="identity-icon" src="https://csdnimg.cn/identity/blog2.png"> </div>
<div class="text"><span>原创文章 6</span><span>获赞 22</span><span>访问量 1万+</span></div>
</div>
<div class="right-message">
<a class="btn btn-sm bt-button personal-watch" data-report-click="{"mod":"popu_379","ab":"new","extend1":"个人信息未关注"}">关注</a>
<a href="https://im.csdn.net/im/main.html?userName=xichengfengyulou" target="_blank" class="btn btn-sm bt-button personal-letter">私信
</a>
</div>
</div>
</div>