The rule about Exception is that it has be be handled or declared and the overriding method can't throw any checked exception that are not declared for the overridden method. But why am I being forced to declare and handle the exception in the below code.
//Removing throws clause
class Overriding{
protected void
test(
String s){
System.out.println("In the Superclass Method test " + s);
}
public static void main(String arg[]){
Overriding superOver = new Overriding();
Override subOver = new Override();
try{
superOver.test("Hello super");
System.out.println();
System.out.println();
subOver.test("Hello sub");
}catch(IllegalAccessException e){
System.out.println(e);
}finally{
System.out.println("This is always execute");
}
}
}
class Override extends Overriding{
protected void test(String s)throws IllegalAccessException{
System.out.println("In method test of subclass " + s );
}
}
Removing the throws clause gives the following error message -
The method void test declared in the class Override cannot override the method of the same signature declared in the class Overriding. Their throws clause are incompatible
protected void test(String s) throws IllegalAccessException
//comment the catch block add the throws clause
class Overriding{
protected void test(String s)throws IllegalAccessException{
System.out.println("In the Superclass Method test " + s);
}
public static void main(String arg[]){
Overriding superOver = new Overriding();
Override subOver = new Override();
try{
superOver.test("Hello super");
System.out.println();
System.out.println();
subOver.test("Hello sub");
/*}catch(IllegalAccessException e){
System.out.println(e);*/
}finally{
System.out.println("This is always execute");
}
}
}
class Override extends Overriding{
protected void test(String s)throws IllegalAccessException{
System.out.println("In method test of subclass " + s );
}
}
Commenting the catch block gives the following error
Exception java.lang.IllegalaccessException must be caught or it must be declared in the throws clause of this method
superOver.test("Hellow super");
When both throws clause and catch block is given the programme give not error message.
In case of NullPointerException(uncheckedexception) we need to either handle or declare the exception. Why is that so?