ParseException Java Example Program


Syntax

try{
   // Do something
}catch(java.text.ParseException e){
   //Do something with caught exception
}

ParseException Example Program

public class ParseException {
    static void convertDateFormat(String inputDate){
        try{
            SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
            Date date = sdf.parse(inputDate);
            SimpleDateFormat outputsdf = new SimpleDateFormat("yyyy-MM-dd");
            String outputDate = outputsdf.format(date);
            System.out.println("After changing date format to yyyy/MM/dd : "+outputDate);
        }catch(java.text.ParseException e){
            System.out.println("Some error occurred while converting date formats. Exception is : "+e.toString());
        }
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter date in dd/MM/yyyy format: ");
        String inputDate = scanner.nextLine();
        convertDateFormat(inputDate);
    }
}

Sample Output 1

Enter date in dd/MM/yyyy format: 
qwerty
Some error occurred while converting date formats. Exception is : java.text.ParseException: Unparseable date: "qwerty"

Sample Output 2 

Enter date in dd/MM/yyyy format: 
12/07/2017
After changing date format to yyyy/MM/dd : 2017-07-12