• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriding and exceptions declaration

 
Adolfo Eloy
Ranch Hand
Posts: 146
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Matthew Brown
Bartender
Posts: 4565
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 5349
50
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 146
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4565
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or a mis-transcription of the original question. Good catch!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic