«^»
9.2. Altering Date to deal with invalid dates

The Date class given earlier can be modified to deal with invalid dates in the following way:

0687: // A class for representing values that are dates.
0688: // Barry Cornelius, 20th September 1999
0689: import java.util. StringTokenizer;
0690: public class Date 
0691: {
0692:    private int iYear;
0693:    private int iMonth;
0694:    private int iDay;
0695:    ...
0696:    public Date(final int pYear, final int pMonth, final int pDay) 
0697:           throws InvalidDateException
0698:    {
0699:       iYear = pYear;  iMonth = pMonth;  iDay = pDay;
0700:       iCheckDate();
0701:    }
0702:    ...
0703:    public int getYear()
0704:    {
0705:       return iYear;
0706:    }
0707:    ...
0708:    public void setYear(final int pYear)
0709:           throws InvalidDateException
0710:    {
0711:       iYear = pYear;
0712:       iCheckDate();
0713:    }
0714:    ...
0715:    private void iCheckDate()
0716:           throws InvalidDateException
0717:    {
0718:       if (iYear<1900 || iYear>2100 ||
0719:           iMonth>12 || iDay>31)
0720:       {
0721:          throw new InvalidDateException();
0722:       }
0723:    }
0724: }
The Date class requires a file containing the following supporting class:
0725: //                                              // InvalidDateException.java
0726: public class InvalidDateException extends Exception {
0727:    public InvalidDateException() {
0728:       super();
0729:    }
0730: }

The following version of the NoelProg program contains some code that catches the exceptions caused by inappropriate uses of the constructors and methods of this new version of the Date class:

0731: ...
0732: public class NoelProg
0733: {
0734:    public static void main(final String[] pArgs)
0735:           throws InvalidDateException,IOException
0736:    {
0737:       final Date tNoelDate = new Date(1999, 12, 25);
0738:       System.out.println("tNoelDate is: " + tNoelDate);
0739:       final BufferedReader tKeyboard =
0740:                     new BufferedReader(new InputStreamReader(System.in));
0741:       Date tOtherDate = new Date();
0742:       while (true)
0743:       {
0744:          System.out.println("Type in the date, e.g., 1999-12-25");
0745:          final String tOtherDateString = tKeyboard.readLine();
0746:          try {
0747:             tOtherDate = new Date(tOtherDateString);
0748:             break;
0749:          }
0750:          catch(InvalidDateException pInvalidDateException) {
0751:             System.out.println("Invalid date");
0752:          }
0753:       }
0754:       System.out.println("tOtherDate is: " + tOtherDate);
0755:       ...
0756:    }
0757: }