1

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?

4
  • Your try/catch there at the bottom has a different purpose, doesn't it? The ParseException try/catch is all that's needed in that parsedDate function. Apr 20, 2016 at 14:59
  • @RobertHarvey hmm, what will exception catch additionally?
    – ChrisW
    Apr 20, 2016 at 15:10
  • 2
    The method's name should be a verb like parseDate(String dateString) or parseCalendar(String dateString); . Apr 20, 2016 at 15:22
  • main can be declared to throw exceptions. They'll be caught by the VM's uncaught exception handler and their stack traces will be printed. Apr 27, 2016 at 7:07

1 Answer 1

7

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.

3
  • Ah, right. One more reason to not bother with checked exceptions. Apr 20, 2016 at 15:13
  • 1
    The simple solution is not to declare that your code may throw exceptions, when it won't. In general "throws Exception" is a bad code smell in anything but throwaway code you don't intend to maintain. If you're using a good IDE, such as Eclipse, then make use of its ability to warn you of un-caught exceptions. If it doesn't flag any, there's no need to add any new "throws" or "catch" clauses.
    – Simon B
    Apr 20, 2016 at 16:02
  • Anyways. If null is not a processable result, don't return null. Let ParseException be thrown. In this example looks like null Calendar means the end of the process. Just keep the catch and remove the if
    – Laiv
    Apr 20, 2016 at 18:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.