Win a copy of Murach's Java Programming this week in the Beginning Java forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

OCP Java 8 Study Guide Ch. 8 Review Question 5 Answer p. 565 (Sybex)  RSS feed

 
Donald Colvin
Greenhorn
Posts: 13
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer to Ch. 8 Review Question 5 includes choice E as correct, giving the explanation: "The append method throws an IOException."

I disagree.  In the abstract class Writer the append methods (as well as flush(), which the question's code also calls) are all declared as throws IOException, but in the question's code the Writer object w must be a PrintWriter, because it's obtained from a call to c.writer() (which has a return type of PrintWriter).  For PrintWriter, the methods are overridden and never throw I/O exceptions (per the class documentation).  So how is answer E correct?
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37051
507
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Donald,
Good question! We were thinking that E is correct because you have to declare an IOException when putting that code in a method. Since the type of the variable is Writer, Java doesn't "know" that it is really PrintWriter and therefore doesn't throw an exception. Declare rather than throw would have been better language here.
 
Donald Colvin
Greenhorn
Posts: 13
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the clarification!  Agreed that you'd have to declare (or catch) IOException to use that code in a method because of w being declared as a Writer rather than a PrintWriter.

Indeed, the way the answer was worded ("An IOException might be thrown") made me see it as false because the actual methods invoked at runtime are those on PrintWriter which declare no checked exceptions and so they in fact cannot actually throw an IOException.

On second thought, I guess one could argue that "An IOException might be thrown" could nevertheless be true even when calling a method that does not declare throwing anything.  How so?  Consider:

Q. Does the method throw an IOException?  Or not?  :-)  Now I'm just having fun, but I do hope the actual exam question and answer wording will be less ambiguous.
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 37051
507
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Donald,
On the real exam, it is easier because you know how many answers are correct. This is good because you can use it as a tie breaker if something like this comes up!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!