javaparseexception

ParseException Java


I am writing an appointment program that allows the user to input appointment dates, description, and type of appointment. Everything works correctly until they make a selection to "Print Range" which prints a range of dates, when they choose to do this it tells them to enter START date and an END date, the program then pulls all of the appointments from between those dates and displays them into the output box.

Here are the errors I am getting with print range :

AppointmentNew.java:68: unreported exception java.text.ParseException; must be caught or declared to be thrown
        Date lowDate = sdf.parse(stdin.nextLine());
                                ^
AppointmentNew.java:70: unreported exception java.text.ParseException; must be caught or declared to be thrown
        Date highDate = sdf.parse(stdin.nextLine());  
                                 ^
AppointmentNew.java:77: unreported exception java.text.ParseException; must be caught or declared to be thrown
           Date newCurrentDate = sdf.parse(currentDate); 

I think I should probably do a try/catch block but am not real sure of how to do that, and was wondering if someone could provide me an answer or example to fix these errors.

Here is some of my code where I believe the parse error is taking place :

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

public class AppointmentNew 
{
public static void main (String[] args) throws Exception
{

if (choiceNum == 2)
     {
        System.out.print("\n\n\tEnter START Date in mm/dd/yyyy format: ");
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
        Date lowDate = sdf.parse(stdin.nextLine());
        System.out.print("\n\n\tEnter END Date in mm/dd/yyyy format: ");
       Date highDate = sdf.parse(stdin.nextLine());  

        for(int i = 0; i < list.size(); i++)
        {
           int dateSpot = list.get(i).indexOf(" ");
           String currentDate = list.get(i);
           currentDate.substring(0, dateSpot);
           Date newCurrentDate = sdf.parse(currentDate); 

           if (newCurrentDate.compareTo(lowDate) >= 0 && newCurrentDate.compareTo(highDate) <= 0)
           {
              System.out.println("\n\t" + list.get(i));

           }
        }
     }

Solution

  • Parse Exception is checked exception so you must have to handle it. Either by throws or try catch block.

    public static void main (String[] args)
    

    Should be

    public static void main (String[] args) throws ParseException
    

    Or in try catch block

    try {
        //All your parse Operations
    } catch (ParseException e) {
       //Handle exception here, most of the time you will just log it.
       e.printStackTrace();
      }