0%

JavaSE Subclass Method Throw Exception

JavaSE Overriding Methods With Exception

Scenario A

1
2
3
4
5
6
7
8
9
10
11
12
13
class CanNotHopException extends Exceotion{ }

class Hopper {
public void hop() throw Exception{

}
}

class Bunny extends Hopper {
public void hop() throws CanNotHopException{

}
}

Result:

Report error.
Rule 1 - Java knows hop() isn’t allowed to throw any checked exceptions because the superclass Hoppper doesn’t declare any.

Scenario B

1
2
3
4
5
6
7
8
9
10
11
12
13
class CanNotHopException extends Exceotion{ }

class Hopper {
public void hop() throws CanNotHopException {

}
}

class Bunny extends Hopper {
public void hop(){

}
}

Result:

Okay.
Rule 2 - A subclass is allowed to declare fewer exceptions than the superclass or interface.

Scenario C

1
2
3
4
5
6
7
8
9
10
11
12
13
class CanNotHopException extends Exceotion{ }

class Hopper {
public void hop() throws Exception {

}
}

class Bunny extends Hopper throws CanNotHopException {
public void hop(){

}
}

Result:

Okay.
Rule 3 - A subclass is allowed to declare a subclass of an exception type because the superclass or interface has already taken care of a broader type.

These above-mentioned rules only apply to checked exceptions.

Scenario D

1
2
3
class Bunny extends Hopper {
public void hop() throws IllegalStateException{ }
}

Result:

Okay.
Rule 4 - declare new runtime exception in a subclass method that the declaration is redundant


Conclusion

  • checked exception, never subclass throws more exception than superclass
  • unchecked exception, no limitations
  • 用中文总结:
    子类在覆盖父类方法的时候,父类的引用是可以调用该方法的,如果父类的引用调用子类的方法,那么这个多抛出来的异常,就可能处于一种无法被处理的状态。一个修理家电的人,他能够修理冰箱,电脑,洗衣机,电视机。 一个年轻人从他这里学的技术,就只能修理这些家电,或者更少。你不能要求他教出来的徒弟用从他这里学的技术去修理直升飞机。

Reference