C2. Declare that Ping.getInt() throws an Exception.
C3. Wrap the invocation of getInt() in a try / catch block.
Which change(s) allow the code to compile? (Choose all that apply.)
A) Just C1 is sufficient.
B) Just C2 is sufficient.
C) Just C3 is sufficient.
D) Both C1 and C2 are required.
E) Both C1 and C3 are required.
F) Both C2 and C3 are required.
All three changes are required.
The given answer is A and C. However I have a problem. The K&B itself states that the main method cannot declare an exception in its signature because it cannot pass the exception to another method because there is no method lower down the call stack. Here are the exact words from K&B:
Because it's a checked exception, the checkFood() method must declare it, and the main() method must handle it (using a try/catch). Do not have main() declare the exception, because if main() ducks the exception, who else is back there to catch it?
So how can C1 which makes main declare exception in its signature be correct?
Having main() throw an exception is not a good practice, incidently because no one can catch the exception but it certainly is legal. Any method can throw exceptions, main() included. If main() throws an exception, the program stops.
When K&B says, "Do not have main() declare the exception," they are just giving you advice to avoid this. They are not saying that it cannot be done. In fact, it can be done, and is "sufficient" for the code to compile, although it's a bad idea. [ September 01, 2007: Message edited by: marc weber ]
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org
I did that to get a test stubb up to useable code, and did not think it would be allowed. It was. The definition of why that is correct can be resolved by having you think about whether throwing an exception right out of main is correct behaviour for your program
It is correct while you develop code, if you remember to take it out.
"The differential equations that describe dynamic interactions of power generators are similar to that of the gravitational interplay among celestial bodies, which is chaotic in nature."