Confusing line of Code on Page 312, Chapter 6 (Java OCA 8 Programmer I Study Guide)
posted 1 year ago
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.
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!
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?