The below code compiles fine. Can you please tell why it wont throw any error as the two exceptions raised are not in hierarchy. class A{ public void m1() throws ClassNotFoundException{ } } class B{ public void m1() throws RuntimeException{ } }
The below code throws a compile time error. This is same as above code with altering the exception type.
class A{ public void m1() throws RuntimeException{ } } class B{ public void m1() throws ClassNotFoundException{ } } Please clarify.
Thanks, Ravindra.
Remko Strating
Ranch Hand
Joined: Dec 28, 2006
Posts: 893
posted
0
The rule is:
Overriden methods may only throw checked exceptions that are new or broader than these declared by the overridden method
Under no circumstances does the compiler care about RuntimeException-related declarations. You can use a throws clause for them, but the compiler doesn't care. You can catch them or throw them, but the compiler doesn't care. Your declarations for them can conflict or disagree in inherited methods -- the compiler doesn't care. I guess this is what was confusing you above -- you're trying to figure out what the compiler allows with RuntimeExceptions. The answer is that it allows anything at all.
Now, for checked exceptions, the compiler does care. If you override a method with a throws clause, then your child method can either A) have no throws clause at all, or B) have the exact same throws clause, or C) have a throws clause that lists one or more subclasses of the exception type(s) thrown by the parent.
The rule is that you must be able to invoke any method of the subclass exactly the same as a method of the superclass. If the superclass method doesn't declare a checked exception, then throwing a checked exception from the subclass means you would have to use a try-catch or a throws.You can invoke fooMethod like this:-but you can't invoke this sort of thing:-. . . without a try-catch. As far as I can remember:-
It must be possible to call every subclass method the same way you call the superclass method.
If the superclass method "throws" a checked exception/exceptions the subclass method can declare it "throws" the same exceptions or their subclasses or fewer or no exceptions.
You can do anything you want with unchecked exceptions; the compiler doesn't worry about them.
The Bar.fooMethod declaration I showed you earlier won't compile because it declares a new checked exception.
I think that is correct . . .
The Java Language specification says it the other way round; it says the superclass "throws" must declare the same exception or their superclasses as the subclass "throws."
Ravindranath Chowdary
Ranch Hand
Joined: Nov 08, 2006
Posts: 71
posted
0
Hi Friends, Thanks for your good explanation. It is clear now. Friedman, the explanation given by you is very clear.
-Ravindra.
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.