Why ParseException is not caught?

125 Views Asked by At

Why is ParseException not caught here? When I enter a date consisting of more than 4 digits it just accepts it, but it shouldn't as I set lenient to false. When I enter letters for the year I get parse exception, but it's not caught.

Example session with too many digits in the year:

Enter name:
Ievgeniia Leleka
Enter position:
Programmer
Enter year
20023
Worker{name='Ievgeniia Leleka', position='Programmer', year='20023'}

Example with letters for year:

Enter name:
Ievgeniia Leleka
Enter position:
Programmer
Enter year
abc
java.text.ParseException: Unparseable date: "abc"
    at java.base/java.text.DateFormat.parse(DateFormat.java:399)
    at Main.isThisDateValid(Test.java:12)
    at Main.main(Test.java:39)
Worker{name='Ievgeniia Leleka', position='Programmer', year='abc'}
public class Main {

    public static boolean isThisDateValid(String dateToValidate, String dateFormat) {
        if (dateToValidate == null) {
            return false;
        }

        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        sdf.setLenient(false);

        try {
            Date date = sdf.parse(dateToValidate);
        }
        catch (ParseException exc) {
            exc.printStackTrace();
            return false;
        }

        return true;
    }

   
1

There are 1 best solutions below

4
KC Wong On

See the documentation of SimpleDateFormat.parse(): https://docs.oracle.com/javase/8/docs/api/java/text/DateFormat.html#parse-java.lang.String-

The key part being: Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.

So if you input "1990a" it will not generate a ParseException because 1990 is a valid value for "yyyy".

But if you input "a1990" it will throw ParseException.

You should include your input and output in the question.

A related question shows how you can be sure it is using the whole string: Force SimpleDateFormat to parse the whole string