Exception while validating a date string in Java
<p>I have found nice function which is validating the format and correctness of date <code>String</code>. I wanted to upgrade it to validate only <code>&gt;= 1900</code> years. </p>

<p>So this is what I found:</p>

<pre><code>public boolean isDateValid(String date) {
    try {
        DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
        df.setLenient(false);
        df.parse(date);
        return true;
    } catch (ParseException e) {
        return false;
    }
}
</code></pre>

<p>And this is my upgraded version:</p>

<pre><code>public boolean isDateValid(String date) {
    try {
        DateFormat df = new SimpleDateFormat("dd-MM-yyyy");
        df.setLenient(false);
        df.parse(date);
        Integer year = Integer.parseInt(date.substring(6, 10));
        if (year&gt;= 1900)
            return true;
        else
            return false;
    } catch (ParseException e) {
        return false;
    }
}
</code></pre>

<p>So instead of returning true I am checking if the <code>year</code> variable is greater or equal to 1900. The problem is when I run this function with <code>"12-12-1xxx"</code> (<strong>edit</strong>: or <code>"12-12-1abc"</code>). <code>NumberFormatException</code> is thrown while parsing year <code>String</code> to <code>int</code>. It definitely should not happen because <code>ParseException</code> should be thrown first, breaking the <code>try {}</code> block.</p>

<p>It looks like validation from first listing does not work properly because it accepts every <code>"yyyy"</code> part which begins with a number. Yet everything works fine for <code>"12-12-xxxx"</code> (<strong>edit</strong>: or <code>"12-12-abcd"</code>).</p>

<p><strong>EDIT:</strong></p>

<p>Stop voting down my question and focus while you are reading. The question is very clear: why new SimpleDateFormat("dd-MM-yyyy").parse("12-12-1xxx") does not throw a ParseException? </p>