Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

exception

 
sree visu
Ranch Hand
Posts: 133
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if Exception1,Exception2 are subclasses of Exception and Exception3 is a subclass of RuntimeException which of the following are correct regarding the following code


my doubt here is weather the answer is only RuntimeException or both Exception3 and RuntimeException..I hope the answer is RuntimeException

please clarify

___________________________
SCJP (preparing)
______________________
 
Raghavan Muthu
Ranch Hand
Posts: 3381
Mac MySQL Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the question is not proper!

you have a line



what is the name of this class?

Also can you please paste the other options as well?
 
Deepak Jain
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think the code is:


1) The overriding method CAN throw any unchecked (runtime) exception,
regardless of whether the overridden method declares the exception. (More
in Chapter 5.)

2) The overriding method must NOT throw checked exceptions that are new
or broader than those declared by the overridden method. For example, a
method that declares a FileNotFoundException cannot be overridden by a
method that declares a SQLException, Exception, or any other non-runtime
exception unless it's a subclass of FileNotFoundException.

3) The overriding method can throw narrower or fewer exceptions. Just because an overridden method "takes risks" doesn't mean that the overriding subclass exception takes the same risks. Bottom line: an overriding method doesn't have to declare any exceptions that it will never throw, regardless of what the overridden method declares.

A.test() method declares that it throws two exception two checked exceptions Exception1 and Exception2.
Now B.test() is a legal override because it meets third condition, The overriding method here B.test() does not declare to throw Exception1 and Exception2.

Now the big question is what should C.test() declare ?? Now C.test() wants to override B.test(). Since B.test() does not declare that it throws any exception C.test() cannot throw any checked exceptions that is it cannot declare to throw Exception1 or Exception2 or both. Now as per condition 1 above the overriding method can declare to thrown any RuntimeException regarless of the overriden method is throwing or not and hence the correct answer would be
void test() {
}
or
void test() throws RuntimeException{
}
or
void test() throws RuntimeException, Exception3{
}

or
void test() throws Exception3,RuntimeException {
}

Since both Exception3 and RuntimeException are unchecked exception you can declare anything after the throws clause
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic