my dog learned polymorphism
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Exceptions  and overriding confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Exceptions  and overriding confusion" Watch "Exceptions  and overriding confusion" New topic

Exceptions and overriding confusion

vivyon p

Joined: Apr 04, 2005
Posts: 3

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

Joined: Aug 03, 2002
Posts: 7729
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 ]

Ask a Meaningful Question and HowToAskQuestionsOnJavaRanch
Getting someone to think and try something out is much more useful than just telling them the answer.
ganga prabhu

Joined: Sep 29, 2005
Posts: 10
Hi all

Clear this too.......

when we override a method, why we should have

-->subclass of that exception,
-->Same Exception
-->No Exception

Why We should not have super class of that exception
Priya Jothi
Ranch Hand

Joined: Jul 13, 2004
Posts: 168
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();

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!!.


Mark Spritzler

Joined: Feb 05, 2001
Posts: 17276

Welcome to the JavaRanch! Please adjust your displayed name to meet the

JavaRanch Naming Policy.

You can change it


Thanks! and welcome to the JavaRanch!


Perfect World Programming, LLC - iOS Apps
How to Ask Questions the Smart Way FAQ
I agree. Here's the link:
subject: Exceptions and overriding confusion
It's not a secret anymore!