According to the overriding rule **** The throws clause of the overriding(subclass) method must only specify exceptions are in the throws clause of the overridden(superclass) method. So why the following code is not giving any error.? class sample { void amethod() throws NumberFormatException{} } class sample1 extends sample { public void amethod() throws IllegalArgumentException{} } Thanks for your reply. Sakthivel.
Paul Anilprem
Enthuware Software Support
Ranch Hand
Joined: Sep 23, 2000
Posts: 2547
posted
0
The rule that you have stated in wrong. The rule is "The throws clause of the overriding(subclass) method may only specify the subset of exceptions that are declared in the throws clause of the overridden(superclass) method." And an empty set is a valid subset. Though the above rule has nothong to do with your question. You can see that both ( ie. NumberFormat and IllegalArgumentException) are RuntimeException. So the compiler doesn't complain. For the overriding method, it is as if the overridden method does not declare any exceptions at all. HTH, Paul.
------------------ Get Certified, Guaranteed! (Now Revised for the new Pattern) www.enthuware.com/jqplus
I think the rule can only apply to checked exceptions. Am I right?
Sudhir Bangera
Ranch Hand
Joined: Oct 10, 2000
Posts: 50
posted
0
java.lang.Object | In java sometimes we have to take into account multiple compatible rules. FOr ex. in your case, the overriding rule is correct but there is another general rule about exception which says 'the exeception type specified in the throws clause in the method header can be a superclass of the actual exception thrown.' The exception hierarchy is as shown below :
+--java.lang.Throwable | +--java.lang.Exception | +--java.lang.RuntimeException | +--java.lang.IllegalArgumentException | +--java.lang.NumberFormatException Since IllegalArgumentException is a superclass of NumberFormatException, your code is not giving error. Java guru's, please confirm if this logic is Ok
Viji Bharat
Ranch Hand
Joined: Sep 18, 2000
Posts: 101
posted
0
All: The exception rule that exists for overriding methods in sub classes is only with regard to checked exceptions. i.e. Subclass methods cannot throw (checked) exceptions of classes other than those (checked exceptions) declared by the original method. Since the example quoted here doesn't have checked exceptions, there is no error. The above said rule is not valid for RunTime exceptions. Sudhir, your logic doesn't look correct to me. I don't know if you are trying to get across the logic behind specifying exceptions in try/catch blocks.