Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

K&B Chapter 5 Self-test Question #8

 
Tobie Henderson
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here's the question:
Given:



And the following three possible changes:

C1. Declare that main() throws an Exception.

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?
 
Dave Walsh
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Do not" is different than "cannot."

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 ]
 
Nicholas Jordan
Ranch Hand
Posts: 1282
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Define correct.

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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic