ParseException

java.text.ParseException – How to Solve ParseException

In this example we are going to talk about java.text.ParseException. This is a checked exception an it can occur when you fail to parse a String that is ought to have a special format. One very significant example on that is when you are trying to parse a String to a Date Object. As you might know, that string should have a specified format. If the given string doesn’t meet that format a java.text.ParseException will be thrown.

Ok let’s see that in a code sample:
 
 
 

1. An example of java.text.ParseException

Here is a simple client that sets a specified date format and then tries to parse a String to a Date object:

ParseExceptionExample.java:

package com.javacodegeeks.core.ParseException;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ParseExceptionExample {

	public static void main(String[] args) {
		String dateStr = "2011-11-19";
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        
            Date date;
            
			try {
				date = dateFormat.parse(dateStr);
	            System.out.println(date);

			} catch (ParseException e) {
				e.printStackTrace();
			}
	}
}

The output of this :

Sat Nov 19 00:00:00 EET 2011

Now if you change:

String dateStr = "2011-11-19";

to this:

String dateStr = "2011 11 19";

Try to run the program again, and you will get this error:

java.text.ParseException: Unparseable date: "2011 11 19"
	at java.text.DateFormat.parse(DateFormat.java:357)
	at com.javacodegeeks.core.ParseException.ParseExceptionExample.main(ParseExceptionExample.java:17)

2. How to solve java.text.ParseException

Well, there isn’t much you can do. There is no mystery surrounding this exception :). Obviously, there is something wrong either with the String you are providing to the parse() method, or with the Format you are providing. You should check again carefully both of these aspects, and of course develop a range of tests that confirm the correctness of your Format.

Download Source Code

This was an example on java.text.ParseException. You can download the source code of this example here : ParseExceptionExample.zip

Nikos Maravitsas

Nikos has graduated from the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. During his studies he discovered his interests about software development and he has successfully completed numerous assignments in a variety of fields. Currently, his main interests are system’s security, parallel systems, artificial intelligence, operating systems, system programming, telecommunications, web applications, human – machine interaction and mobile development.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button