• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Exceptions and overriding confusion

 
vivyon p
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

As per the rules of overriding methods in subclass, this code should not compile. But it does compile. How ? I am totally confused. Can anyone please explain ?
[ October 03, 2005: Message edited by: Barry Gaunt ]
 
Barry Gaunt
Ranch Hand
Posts: 7729
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The overriding rules pertain only to checked exceptions. Error is not a checked exception, so let's throw it away:


Now you can see that TestIt.method1 is following the rule of throwing the same, a subset of, or none of the checked exceptions thrown by the overridden method.
[ October 03, 2005: Message edited by: Barry Gaunt ]
 
ganga prabhu
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all

Clear this too.......

when we override a method, why we should have

-->subclass of that exception,
(or)
-->Same Exception
(or)
-->No Exception

Why We should not have super class of that exception
 
Priya Jothi
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ganga,

Observe the following code.

Throwable t = new Exception(); //1

Exception e = new Throwable(); //2

For sure the stmt marked //1 will compile.Do u think //2 also will get compiled?.No it'll never.Casting pblm comes into picture now..which forces the compiler to check the rule u stated in ur post!.


Lets say if u have stmts like this..

Test t = new TestIt();
t.method1();

For hypothetical situation assume the method1 is allowed to throw Throwable(in child class) & Exception(in parent class).Consider the following code for the same.(Surely it wont work.. )



Now consider what if the above snippet runs from the main method???!!!

Ouch..JVM will throw classCastException!!!

Coz it is obvious it cant wrap Throwable object in Exception Reference type.
Compiler is smart enough to identify & prevent these kind of situations!!.


hth..

Regards,
Priya.
 
Mark Spritzler
ranger
Sheriff
Posts: 17278
6
IntelliJ IDE Mac Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"vivyon"-
Welcome to the JavaRanch! Please adjust your displayed name to meet the

JavaRanch Naming Policy.

You can change it

here.

Thanks! and welcome to the JavaRanch!

Mark
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic