What is the Problem With The Code

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
RRRRRR
Posts: 26
Joined: Sun Jul 23, 2017 2:13 am
Contact:

What is the Problem With The Code

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

admin
Site Admin
Posts: 10046
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

Re: What is the Problem With The Code

Post 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.
If you like our products and services, please help us by posting your review here.

RRRRRR
Posts: 26
Joined: Sun Jul 23, 2017 2:13 am
Contact:

Re: What is the Problem With The Code

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

Post Reply

Who is online

Users browsing this forum: No registered users and 83 guests