[Solved] java.text.ParseException in Java with Examples

In this post, I will be sharing how to fix java.text.ParseException in Java with examples. According to Oracle docs, this exception signals that an error has been reached unexpectedly while parsing.

Read Also: [Fixed] java.io.NotSerializableException in Java

java.text.ParseException is a checked exception and it was introduced in JDK 1.1.

Let's dive deep into the topic:

[Fixed] java.text.ParseException in Java with Examples

As always, first, we will produce the java.text.ParseException before moving on to the solution.

1. Producing the exception while parsing a String to a Date object


java.text.ParseException can be produced if you are trying to parse a String to a Date object. You might know that String should have a specified format e.g. dd/mm/yyyy or dd,mm,yyyy. java.text.ParseException will be thrown if the String doesn't meet the specified format as shown below in the example.

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

public class ParseExceptionExample {
    public static void main(String args[]) {
      String dateString = "2022/11/22";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date outputDate; try { outputDate = sdf.parse(dateString); System.out.println(outputDate); } catch(ParseException e) { e.printStackTrace(); } } }


Output:

java.text.ParseException: Unparseable date: "2022/11/22"
     at java.base/java.text.DateFormat.parse(DateFormat.java:399)
     at ParseExceptionExample.main(ParseExceptionExample.java:11)

Explanation


In the above example, we are representing String in yyyy/MM/dd format but try to parse it in a different format i.e. yyyy-MM-dd, hence, we got a ParseException.

  ðŸ’¡ Did You Know?

ParseException is a checked exception, so you must handle it either by try-catch block or throws keyword in method signature.


Solution


You have to check if there is something wrong either with the String you are providing to the parse() method or with the format you are providing. In the above example, we can easily get rid of the ParseException by changing the format to yyyy/MM/dd as shown below:

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

public class ParseExceptionExample {
    public static void main(String args[]) {
      String dateString = "2022/11/22";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
Date outputDate; try { outputDate = sdf.parse(dateString); System.out.println(outputDate); } catch(ParseException e) { e.printStackTrace(); } } }


Output:

Tue Nov 22 00:00:00 GMT 2022

That's all for today. Please mention in the comments if you are still facing the java.text.ParseException in your code.

About The Author

Subham Mittal has worked in Oracle for 3 years.
Enjoyed this post? Never miss out on future posts by subscribing JavaHungry