Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

No exception when parsing date from string

 
Michael Remijan
Author
Ranch Hand
Posts: 131
7
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,
I think I should be getting an exception here but i'm not. I have:
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy", user.getLocale());
When I try to parse an *invalid* date I expected an exception to be thrown:
sdf.parse("99/99/9999");
I am NOT getting an exception and Java returns a java.util.Date object with the toString value:
Thu Jun 07 00:00:00 CDT 10007
Shouldn't the parse() method have thrown an exception? How do I get it to?
 
Tom Blough
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do you think you should get an exception? According to the API the only exception thrown by parse is a NullPointerException, and your invalid date certainly was not null.
 
Michael Dunn
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
toggle on/off the sdf.setLenient(false) to see what happens
 
Tom Blough
Ranch Hand
Posts: 263
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
parse is still not throwing an exception. With leinent off, parse is returning null, and setTime is throwing a NullPointerException.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
According to the API the only exception thrown by parse is a NullPointerException, and your invalid date certainly was not null.
That's true for parse(String, ParsePosition) - but not parse(String) which is defined in DateFormat and not overridden. Michael, could you show the code you're using to parse this?
 
Michael Remijan
Author
Ranch Hand
Posts: 131
7
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Michael Dunn's tip worked for me, thanks Michael. When I set lienient to false, the parsing would not allow dates like 99/99/9999 or 4/40/2004.
If lienient is not working for you, search through your code for "new SimpleDateFormat" and ".getInstance". The first time I tried setting lienient to false did not work because I missed a place in my code where I create a DateFormat object with ".getInstance"
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic