Search code examples
javatry-catchdate-format

What is the use of try-catch in setting a date value in java?


I'm a java newbie going through some training material, and this is one of the questions.

Given a valid DateFormat object df, and

Date d = new Date(0L);
String ds = "December 12, 2012";
//Insert correct code here

What updates d's value with date represented by ds?

A. d = df.parse(ds);
B. d = df.getDate(ds);
C. try{
        d = df.parse(ds);
       }
   catch(ParseException e){ };

The correct answer is C. Why is that so? What is the difference between A and C?


Solution

  • Because parse() can throw a ParseException and it is a checked Exception. Checked Exceptions must be handled by the calling code using a try-catch block or your code must declare that it can throw the Exception , by using a throws clause.

    Checked exceptions are exceptions that the designers of Java feel that your programs absolutely must provide for, one way or another. Whenever you code a statement that could throw a checked exception, your program must do one of two things:

    1. Catch the exception by placing the statement within a try statement that has a catch block for the exception.

    2. Specify a throws clause on the method that contains the statement to indicate that your method doesn’t want to handle the exception, so it’s passing the exception up the line.

    A better code would have been :

    try{
        d = df.parse(ds);
       }
    catch(ParseException e){   
       e.printStackTrace();
       // log the exception
       throw new RuntimeException(e);
    }
    

    Read this for more on Checked Exceptions.