Meaningless Drivel is fun!*
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

Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overriding and exceptions declaration" Watch "Overriding and exceptions declaration" New topic

Overriding and exceptions declaration

Adolfo Eloy
Ranch Hand

Joined: Mar 21, 2009
Posts: 146


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?


Adolfo Eloy
Software Developer
Matthew Brown

Joined: Apr 06, 2010
Posts: 4339

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

Joined: Sep 20, 2010
Posts: 3574

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

Joined: Apr 06, 2010
Posts: 4339

Or a mis-transcription of the original question. Good catch!
wood burning stoves
subject: Overriding and exceptions declaration
Similar Threads
Question about Exceptions
OCP exams - Overriding question
BB && KS Practice Exams - Practice Exam 2, question 29 - wrong answer?
OCPJP 6 Practice exams, exam 2 q 29 error
OCP JP Practice Exam 2 #29