Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Confusing line of Code on Page 312, Chapter 6 (Java OCA 8 Programmer I Study Guide)

 
Suresh Regmi
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have copied and pasted the code from page 312. I did notice that the the line number 6 throws the compile time error asking you to either declare or handle it. This is little confusing for me, since this code by itself conveys that it compiles without any other support.





Solution 1: Declaring within the main method or any other instance or Static method.




Solution 2: Surround with Try catch


 
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
Suresh Regmi wrote:I did notice that the the line number 6 throws the compile time error asking you to either declare or handle it.

Yes, if you add the code snippet to any method, you'll have to handle or declare the Exception thrown from the finally block. But if you look at this code snippet and the explanation in the book, it's obvious the purpose is to illustrate the RuntimeException (at line4) is forgotten and the Exception (at line6) will be thrown (not using this code in a method). But I agree, it's maybe better to have a RuntimeException at line6 as well (so code will always compile).

And to make a proper distinction between the different runtime exceptions, it might even be better to use this code snippetOr this one might even be betterSo when this code snippet is executed, it's really obvious which of these exceptions is actually thrown.

Hope it helps!
Kind regards,
Roel

PS. Please be sure to use code tags when posting code to the forums. Unformatted or unindented code is extremely hard to read and many people that might be able to help you will just move along to posts that are easier to read. Please click this link ⇒ UseCodeTags ⇐ for more information. Properly indented and formatted code greatly increases the probability that your question will get quicker, better answers. I've gone ahead and added the code tags for you. See how much easier the code is to read?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic