Avoid Empty Catch Blocks When Expecting Exception
<p>I am trying to parse dates using <code>SimpleDateFormat</code>. As my service takes in multiple date formats, I have adopted <a href="https://stackoverflow.com/questions/4024544/how-to-parse-dates-in-multiple-formats-using-simpledateformat">this</a> approach:</p>

<pre><code>String[] formats = {
        "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
        "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
        "yyyy-MM-dd'T'HH:mm:ss.SSS-HH:mm",
        "EEE MMM dd HH:mm:ss Z yyyy"};

for (String format : formats)
{
    try
    {
        return new SimpleDateFormat(format).parse(dateString);
    }
    catch (ParseException e) {}
}
return null;
</code></pre>

<p>The rationale behind the <code>try-catch</code> is that if the current date format couldn't parse the <code>dateString</code>, an <code>Exception</code> would be thrown and the code would continue looping until a suitable date format is found, or return <code>null</code>.</p>

<p>The <code>catch</code> block is simply there so the <code>try</code> block would have something following it (a compile error could occur if nothing follows <code>try</code>). </p>

<p>I could leave the code just as it is, but empty <code>catch</code> blocks are bad practice. It would also be confusing for other people to maintain in the future. And it's simply inelegant.</p>

<p>I could put the following in the <code>catch</code> block :</p>

<pre><code>catch (Exception e)
{
    if (!(e instanceof ParseException))
    {
        throw e;
    }
}
</code></pre>

<p>But again, the code inside serves no purpose as no <code>Exception</code> other that a <code>ParseException</code> could be thrown by the <code>try</code> block (I check for <code>NullPointerException</code> earlier in the code). Using a <code>final</code> block instead of a <code>catch</code> block would be useless also.</p>

<p>Is there a way to avoid the empty or useless <code>catch</code> block? Could <code>try-catch</code> be avoided completely?</p>

<hr>

<p>Similar Questions (but not quite):</p>

<p><a href="https://stackoverflow.com/questions/26537048/avoiding-an-empty-catch-clause">Avoiding an empty catch clause</a></p>

<p><a href="https://stackoverflow.com/questions/16715664/empty-catch-blocks">Empty catch blocks</a></p>

<p><a href="https://softwareengineering.stackexchange.com/questions/16807/is-it-ever-ok-to-have-an-empty-catch-statement">Is it ever ok to have an empty catch statement?</a></p>