• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

question on exception (Java OCA 8 Programmer I Study Guide, Sybex)

 
Ramya Subraamanian
Ranch Hand
Posts: 178
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a question from oca programmer guide by Jeanne and Scott.

Which of the following can be inserted into Lion to make this code compile? (Choose all that apply)


A. public void roar(){}
B. public void roar() throws Exception{}
C. public void roar() throws HasSoreThroatException{}
D. public void roar() throws IllegalArgumentException{}
E. public void roar() throws TiredException{}


why cant i have B as my option. HasSoreThroatException is a subclass of Exception right then , why cant it be used.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ramya Subraamanian,

First of all, a warm welcome to CodeRanch!

Ramya Subraamanian wrote:why cant i have B as my option. HasSoreThroatException is a subclass of Exception right then , why cant it be used.

In short: only valid overrides of the roar() method of the Roar interface. The method declares to throw a HasSoreThroatException which is a checked exception. One of the rules is about the exception list (that's the throws-clause in the method declaration). The overriding method can throw no exceptions, the same exceptions or narrower or fewer exceptions; but broader checked exceptions are not allowed. HasSoreThroatException IS-A Exception, meaning Exception is the superclass of HasSoreThroatException. And thus Exception is a broader exception than HasSoreThroatException, therefore it's not allowed. Because if the method declares to throw Exception, it can throw any subclass. So you could throw HasSoreThroatException, FileNotFoundException, IOException, SQLException, and so on. But the roar() method of the Roar interface only defines the HasSoreThroatException.
Assume you would have this additional checked exceptionThen this code snippet would compile successfully, because HasReallySoreThroatException IS-A HasSoreThroatException, so HasSoreThroatException is the superclass of HasReallySoreThroatException. Therefore if the method throws a HasReallySoreThroatException, the method throws a narrower checked exception than defined in the overridden method (which is allowed)

A more detailed explanation (based on another code snippet) with a bunch of additional code examples can be found in this (excellent) post.

Hope it helps!
Kind regards,
Roel
 
Ramya Subraamanian
Ranch Hand
Posts: 178
17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got it now . Thank you Roel ;)
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic