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):
NullPointerException
, depending upon wheredateString
comes from. – Nacatch
or afinally
, then you would not need or want atry
, either. As far as I can determine, thecatch
block is there for the usual reason: you want to catch (certain) exceptions. – GermanismParseException
. Then, if aRuntimeException
is thrown, that will be propagated; and the compiler guarantees that no checked exception exceptParseException
is thrown. So, that is just a complicated way of getting basically the same behaviour. – Na