PhotometricStereo PhotometricStereo - 4 months ago 16
Java Question

Avoid Empty Catch Blocks When Expecting Exception

I am trying to parse dates using

SimpleDateFormat
. As my service takes in multiple date formats, I have adopted this approach:

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;


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

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

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

I could put the following in the
catch
block :

catch (Exception e)
{
if (!(e instanceof ParseException))
{
throw e;
}
}


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

Is there a way to avoid the empty or useless
catch
block? Could
try-catch
be avoided completely?




Similar Questions (but not quite):

Avoiding an empty catch clause

Empty catch blocks

Is it ever ok to have an empty catch statement?

Answer

Your code is fine. It is intentional and reasonable in this case to take no action when the SimpleDateFormat throws a ParseException. The only thing I would do differently is insert a documentary comment to that effect:

for (String format : formats)
{
    try
    {
        return new SimpleDateFormat(format).parse(dateString);
    }
    catch (ParseException e) {
        // The string does not conform to the trial format.
        // Just try the next format, if any.
    }
}

It is bad form to use empty catch blocks to avoid dealing with an exception that should be handled, instead. That's not what you're doing -- yours is the unusual case in which the correct handling is to do nothing.