This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
a.Someone tries to set the capacity of a PackingBox to a negative value. b.A syntax error is found in a configuration file that an object uses to set its initial state. c.A method that searches for a programmer-specified word in a string array cannot find any occurrence of the word.
Personally I would throw an exception for B and quite possibly A as well. It depends mostly on whether "someone" in A is a user or a programmer. I'd definitely throw an exception if it's a programmer. Even if it's a user, I might throw an exception from one method, and catch it in another. C is possible too, but unlikely unless there us some reason to expect that the array must contain the string in order for the program to function correctly. I'm not usually interested in being "graceful" - I want to make errors easy to detect, then fix them. But really, there is no one absolute answer here. I think we could probably imagine circumstances for each of these where you could argue either way. But in my experience, for most circumstances that I can imagine, I would throw an exception for B, maybe A, but probably not C. [ April 11, 2008: Message edited by: Jim Yingst ]
I think that as a user I'd be pretty miffed if an Exception got thrown on A.
It's as though accidentally trying to use my library card in the ATM machine causes a hole to open up under me, dropping me into a dark box which suddenly spits me out a few blocks away. I wouldn't know how to recover. Sheesh, all I wanted was 20 bucks that are mine in the first place.
But if "someone" is a programmer, and a negative value in the PackingBox might cause subtle bugs in my Crate class, potentially leading to a weird error where the freight ship might sink if it encountered a hurricane during a full moon (and only if whales are singing) I'd be pretty relieved if an exception was thrown. Lives could be saved!
Then again, if my PackingBoxes are just for the move across town and a negative value would just cause one of the PackingBoxes to be empty I might notify the user/programmer and they could deal with it or not as they pleased. An extra box, or an extra trip across town. Not such a huge deal.
I guess one question would be "is the user going to be around to deal with the problem"? With the configuration file in B if you try ignoring it or sending friendly messages to the user, you are likely to get some pretty crazy behavior (if any).