I am trying to parse a string in java that comes like this: String test="Unknown" But users data wants this string as date. Can it be a way to parse or avoid this case? For example that date to be taken like empty, instead of unknown?
1 Answer
Catch the exception when the Date can't be parsed and set the Date to null or some placeholder value that you know to represent an unparseable date.
edit: As GhostCat points out in the comments, you may want only "Unknown" to be treated this way, and not unparseable dates in general. Error handling can get complicated... at the very least you should be logging when the date can't be parsed. The exact requirements haven't been stated in your question so how you need to handle errors is not known.
6 Comments
Erich Kitzmueller
I would rather check for
"Unknown" specifically than just handle all parse errors as if they were unknown. Maybe some date strings are given as "21.12.2018" instead of the expected "12/21/2018" and then you should at least leave a warning in the logfile.GhostCat
Exactly, indiscriminately turning all parsing errors into that single case is bad advise.
swpalmer
@ErichKitzmueller Yes, totally agree that these cases should be logged at the least. "Unknown"could be set to a specific token Date value that represents the "Unknown" data, but care needs to be taken so the token Date values aren't interpreted elsewhere as "real" dates. There should be another indicator or wrapping class so bad dates don't get exposed.
Ester
Thanx a lot, I managed to solve it by exceptions
Anonymous
Logging is no solution. You will want to handle the case of
"Unknown" separately exactly in order to avoid that error handling gets more complicated than necessary. |
"Unknown"? This seems pointless. That is not a date in any meaningful sense.nullor it has an instance ofLocalDateor a similar object.