Page 1 of 1

What is the Problem With The Code

Posted: Sun Jul 23, 2017 2:16 am
by RRRRRR
Hello Everyone I am new at this Forum and I wanted to ask a question in this topic-> Exception Handling with Method Overriding in Java

There is a rule that-> If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception.

then why not this code is giving me Compile Time Error->

import java.io.*;

class Parent{

void msg()throws ArrayIndexOutOfBoundsException
{
System.out.println("parent");
}

}

class TestExceptionChild2 extends Parent{

void msg()throws IndexOutOfBoundsException
{
System.out.println("child");
}

public static void main(String args[]){

Parent p=new TestExceptionChild2();

try{

p.msg();

}catch(Exception e){}

}

}



See I have made Parent Class method msg() to thorw ArrayIndexOutOfBounds Exception which is subclass of IndexOutOfBoundsException and in Derived Class method msg() I have thrown

IndexOutOFBoundsException which is parent of ArrayIndexOutOfBounds . Then why not the code giving me Compile Time Error. Please Help...

Thanks In Advance...

Re: What is the Problem With The Code

Posted: Sun Jul 23, 2017 2:46 am
by admin
All rules about exceptions are always only about checked exceptions.

Unchecked exceptions, i.e. exceptions that extend directly or indirectly from RuntimeException (or Error) can be thrown anywhere without declaring them in the throws clause. They can also be added to throws clause without any consequence. The compiler doesn't care about such exceptions, that is why they are called "unchecked" exceptions. Meaning, the compiler doesn't "check" them.

Now, coming to your question, IndexOutOFBoundsException extends RuntimeException and is therefore an unchecked exception. So any method is free to declare or not declare it in its throws clause.

Re: What is the Problem With The Code

Posted: Sun Jul 23, 2017 3:40 am
by RRRRRR
Means that for Unchecked Exceptions or Errors Method Overriding rule dose not matter, it matters only for Checked Exceptions.

Thank you very much for your quick reply.