Java Programming – Improving Try/Catch Blocks

javapatterns-and-practicesprogramming practices

I'm a python programmer trying to get to grips with Java's inflexibility; I'm trying to parse a date from a string into a Calendar object

private Calendar parsedDate ( String dateString ) throws Exception {
  Calendar calendar = Calendar.getInstance();
  DateFormat format;
  Date date;
  try {
    format = new SimpleDateFormat("dd/MM/yyyy");
    date = format.parse(dateString);
    calendar.setTime(date);
  } catch (ParseException e) {
        System.out.print("wrong date format");
        calendar = null;
  }
  return calendar;
}

----
Main method
----

Calendar pd;
try {
  pd = parsedDate("01/01/2016");
  if(pd != null) {
    // do stuff
  } else {
    System.out.println("A problem");
  }
} catch (Exception e) {
  System.out.println(e.getMessage());
}

I was hoping I could make the main method code snippet more succinct by taking out the try/catch – since I'm already testing if it's null, but if I do that then Java (well, eclipse) complains about Unhandled exception type Exception – do I really need both sets of try/catch, or is there a better way of achieving what I want?

Best Answer

Your parsedDate method doesn't need the throws Exception clause because the exception is already being caught.

The compiler looks at the method signature when a method is called and sees throws Exception, so it expects you to handle it.

Related Topic