Originally posted by Amy Caine:
Now, which way is recommended? Which way is the best design?
Glad to help! For this question, however, the answer is always "it depends on what you need." Do you need to loop and keep asking the user for a new month until they supply you with a valid one? If so, you'll want to wrap the JOptionPane call and parsing inside a while loop.
Many people don't like the use of break, but I think it makes perfect sense for cases like this. Otherwise you'd have to repeat the validity
test as the loop condition, but you already know month is invalid starting out, and you can use break instead to drop out once it's valid.
As I stated in my previous post, I generally shrink my try blocks down to the smallest size possible. The main reason is that then it's very clear which code can throw the exception. If you have a giant 50-line try block with three difference catch blocks, you'll have to read the full code to figure out which lines can cause errors. By splitting it up you communicate more information to the next person to read the code, possibly yourself in six months.
However, there are also many times where I have a block of code that may throw several types of exceptions, and I either want the whole thing to work or abort. In this case, I'll leave one big try block since I'm not going to recover or loop when an exception is thrown. I tend to do this in initialization code where either it all works or the program aborts.
When you're dealing with users, it's nice to give them an opportunity to recover from typos. But if you're reading configuration values from a file, all you can do when an error occurs is bail out and let the controller log an error message.
[ March 26, 2005: Message edited by: David Harkness ]