Win a copy of Head First Agile this week in the Agile forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Exceptions  RSS feed

 
Maureen Charlton
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a main method in the VehicleRecord class:
the date is a String containing three digits and a letter


At present the main method is catching the exception when a character i.e. a letter is put in a four digit date.

I want the method to catch the exception and can't work out why it isnt

My method catching the exception is:


I would appreciate any suggestions?

[ EJFH: Let Emacs format the code so we can see structure more easily. ]
[ January 29, 2007: Message edited by: Ernest Friedman-Hill ]
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If there's an invalid character, then NumberFormatException throws an exception, inside the try block. Your matching catch block then unconditionally throws an InvalidRecord exception, and its this InvalidRecord that main() catches.

If you don't want the method to throw an exception in this case, then all you have to do is... not throw one! Your catch block should do something else -- just print a message?

Now, my personal opinion, likely to be shared by many here, is that having your validateDate() method throw an exception for an invalid value, and leaving it up to main to print the message, is an excellent design, for many reasons. One of these is that such a method is easy to test. Another is that the method wouldn't need to be changed when the app becomes a GUI or Web application later in its life -- i.e., the method is more reusable. So I'm not at all sure that your current design should be changed -- except to remove the existing print statements inside validateDate().
 
Maureen Charlton
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ernest
Many thanks for your response.
I'm still confused though as I expected the output to be:
"Date not valid: Needs to be ALL digits" as thrown in my caught Number FormatException in the validateDate method which throws InvalidRecord

Instead I'm getting an output of "Date Not Valid" as caught in my main method?

Thanking you in advance
 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are not outputing the message of your InvalidRecord exception anywhere. Try this:

or; much, much better:
 
Maureen Charlton
Ranch Hand
Posts: 218
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul,

THANK YOU
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!