1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
/*
异常的注意事项:
1,子类在覆盖父类方法时,父类的方法如果抛出了异常,那么子类的方法只能抛出父类的异常或者该异常的子类。
2,如果父类抛出多个异常,那么子类只能抛出父类异常的子集。
简单说:子类覆盖父类,只能抛出父类的异常或者子类或者子集。
注意:如果父类的方法没有抛出异常,那么子类覆盖时绝对不能抛。子类不能抛出比父类多的异常。就只能try。。。catch
*/
class
A
extends
Exception{
A(String msg){
super
(msg);
}
}
class
B
extends
A{
B(String msg){
super
(msg);
}
}
class
C
extends
Exception{
C(String msg){
super
(msg);
}
}
/*
Exception
---A
---B
---C
*/
class
Parent{
void
show()
throws
A{
throw
new
A(
"抛出A异常!"
);
}
}
class
Child
extends
Parent{
void
show()
throws
B{
throw
new
B(
"抛出B异常!"
);
}
}
public
class
PC{
public
static
void
main(String[] args){
new
PC().methods(
new
Parent());
}
static
void
methods(Parent p){
//如果参数是Parent 的子类,也就是多态时,子类中抛出了父类没有的异常类型,
//下面的代码那就不能被处理了!
try
{
p.show();
}
catch
(A e){
System.out.println(
"处理完异常!"
);
}
}
}
|
本文转自 小眼儿 博客园博客,原文链接:http://www.cnblogs.com/hujunzheng/p/3872781.html,如需转载请自行联系原作者