Forums Register Login

overriding question

+Pie Number of slices to send: Send
/*

compiling code below was successful, i had thought the method overriding by B.doo() would fail without the declaration "throws Exception".

What's the overriding rule regarding it?

Thanks!

*/


class A {

void doo() throws Exception {}

}

class B extends A {

void doo() {}

}
+Pie Number of slices to send: Send
Hi Bob,

When you override a method, make sure for 2 things regarding exceptions, is that your overriden method cannot throw broader checked exception and if it dosn't throw any checked exceptions also it works. It can throw any run time exceptions.
+Pie Number of slices to send: Send
just found the rule:

overriding method may throw fewer or narrower checked exceptions, or any unchecked exceptions.
+Pie Number of slices to send: Send
Thanks, Jothi!
+Pie Number of slices to send: Send
Try the following cod eyou will get error

class A {

void doo() throws Exception {System.out.println("sys");}

}

public class B extends A {

void doo() {System.out.println("sys1");}

public static void main(String s[]) {

A a=new Test();

a.doo();//unreported exception error

Test t=new Test();
t.doo();
}
}

ie Overriding method not declared the exception, declared by the super class
+Pie Number of slices to send: Send
class A {

void doo() throws Exception {System.out.println("sys");}

}

public class Test extends A {

void doo() {System.out.println("sys1");}

public static void main(String s[]) {

A a=new Test();

a.doo();

Test t=new Test();
t.doo();
}
}
+Pie Number of slices to send: Send
Hi Suguna,

Consider the code below,



The above works fine and I'n not saying void test() throws Exception in my subclass. It works just fine. The point is if any method says to the world that it might throw an exception, then callers of that method should make arrangements to handle any exceptional condition that might occur. It has got nothing to do with overriding. Hope you understood the concept.
+Pie Number of slices to send: Send
Hai Jyothi,

Thanks for your deatiled answer... so you say compiler wont check whether the overriding method throws exception or not,but when we call the overridden method,programmer should handle it as it throws checked exception other wise it would be an unreported exception and compiler spit an error...am rite?

Harish
I would challenge you to a battle of wits, but I see you are unarmed - shakespear. Unarmed tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 778 times.
Similar Threads
Why? null is not a common object,then what it is?
exception question
Question on catching checked exception together with its super type
why is that output ?
question on overriding the method that throws checked exception
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 05:44:33.