constructors with exceptions
class ClassC{
ClassC() throws ArrayIndexOutOfBoundsException{
}
public void method() throws Exception{
System.out.println("Super class");
}
}
class ClassB extends ClassC{
ClassB() throws NullPointerException{
}
}
this works..... but.....
class ClassC{
ClassC() throws Exception{
}
public void method() throws Exception{
System.out.println("Super class");
}
}
class ClassB extends ClassC{
ClassB(){
}
}
but this doesnt.... can someone explain this...?
hi TimTheEnchantor
i got dat point.... but in the code below the subclass constructor also calls the superclass which throws arrayindex exception. But the subclass constructor doesnt still it works fine... why?
in this case also the subclass must throw arrayindex exception.
isnt?
public class SuperConstructor {
SuperConstructor() throws ArrayIndexOutOfBoundsException{
}
}
class SubConstructor extends SuperConstructor{
SubConstructor(){
}
}
hi....TimTheEnchantor
let me make my doubt more clear.
If the superclass default constructor throws Exception then it becomes mandatory for the subclass to throw Exception too. But if the superclass default constructor throws any RuntimeException like NullPointer or Arrayindexoutofbounds exception the subclass need not throw it. Why?
That's the difference between checked and unchecked exceptions.
Checked exceptions :
- represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files)
- are subclasses of Exception
- methods are obliged to establish a policy for all checked exceptions thrown by its implementation (either pass the checked exception further up the stack, or handle it somehow)
Unchecked exceptions :
- represent defects in the program (often invalid arguments passed to a non-private method)
- are subclasses of RuntimeException, and are usually implemented using IllegalArgumentException, NullPointerException, or IllegalStateException
- methods are not obliged to establish a policy for the unchecked exceptions thrown by its implementation (and they almost always do not do so)