Can we override a super class method that is throwing an unchecked exception with a checked exception in the subclass?
Asked
Active
Viewed 4,394 times
2
-
2What is keeping you from making an example and see for yourself? :) – Janez Kuhar May 21 '20 at 08:43
-
Lets say you have method like `void method(SuperType st){ .. st.foo(); }` and you pass to that method instance of class which overrides `foo()` to throw checked exception. Will previously written code be safe? – Pshemo May 21 '20 at 08:48
-
Sub class object IS A super class object as well. Hence any place an object of sub class should fit into where an object of type Super class is expected, without any compilation exception. Just imagine you throwing a checked exception from a sub class by overriding a method, imagine what would happen to callers of the method who expected the object of type super class. Now should they automatically start to not compile or what ?. What will happen when u inject the sub class object to such pre existing callers ? Once you think like this, you get the answer yourself. – nits.kk May 21 '20 at 08:52
-
Ideal way to get answers is to think, what wrong could happen if this is allowed, will there be any ambiguity if this is allowed. Once your mind think and gets the answer for you then you should be excited to verify it using a demo program and then verify it using the document of JLS. this is best way to learn. Cramping the rules will not help, you will forget them. – nits.kk May 21 '20 at 08:56
1 Answers
1
No, you cannot.
The sub-class method cannot throw any checked exception not covered by the throws
clause of the base super class method.
In other words, the sub-class method can throw a checked exception only if it appears in the throws
clause of the super class method or if it is a sub-class of an exception that appears in that throws
clause.
This makes sense, since a user of the super class is only aware of the contract of the super class method, so how would they know that they have to catch some additional exception not mentioned in the throws
clause of the super class? They can't and shouldn't be aware of all the sub-classes that override that method (some of which may not have been written yet).

Eran
- 387,369
- 54
- 702
- 768
-
Thank you! Clearly understood now.The second reference above helped too. – Ador68 May 21 '20 at 08:54
-
@Ador68 , read my comment to your question, It will be helpful in future for your learning. All the best – nits.kk May 21 '20 at 08:58