aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overriding and exceptions declaration Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overriding and exceptions declaration" Watch "Overriding and exceptions declaration" New topic
Author

Overriding and exceptions declaration

Adolfo Eloy
Ranch Hand

Joined: Mar 21, 2009
Posts: 146

People,

I think this question has a wrong answer in the book.

Given the code:


Question from OCP Java SE 6 Programmer Practice Exams.



Which of the following methods, inserted independently at line 11, compiles? (Choose all that apply).

A. void think() throws Exception { }
B. void think() throws FileNotFoundException { }
C. public void think() { }
D. protected void think() throws IOException { }
E. private void think() throws IOException { }
F. void think() { int x = 7/0; }

My answers are: C, F
Book answers are: B, C, D and F

Could anybody help me to understand what is going on at this question?

Thanks.


Adolfo Eloy
Software Developer
OCPJP 6
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4467
    
    8

When you override a method, you can be more specific when throwing exceptions, and you can be more permissive when specifying access. The other way round doesn't work.*

Given that, can you see why B & D should compile?

* Here's an example that demonstrates why it works that way with exceptions

That try/catch block should be OK - it's consistent with the Superclass reference type. But what happens on line 14 if the overridden method throws an Exception? It isn't handled anywhere. Line 15 is fine, though, because FileNotFoundException is-an IOException, and so it's already handled.

Try a similar example with the access specifiers - the principle is very similar.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3649
    
  17

Actually, Adolfo is correct. Strictly speaking, only C and F would compile. I think the confusion arises from the fact that the main method signature should actually be:
I think this is probably an oversight in the book.
Adolfo Eloy
Ranch Hand

Joined: Mar 21, 2009
Posts: 146

Thanks for all replies.
I really think strictly about this question, because along my studies I was prepared to be strictly with exam questions.
I hope it's a good think when doing my real exam next week.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4467
    
    8

Or a mis-transcription of the original question. Good catch!
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Overriding and exceptions declaration