0

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?

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
mankand007
  • 952
  • 2
  • 10
  • 22
  • 3
    Use another training material. Something which marks correct an answer which consists in swallowing exceptions must be avoided, at all cost. – JB Nizet Jul 10 '13 at 20:36
  • 1
    @JBNizet And did you catch that semicolon in the end? I mean, REALLY :) – Marko Topolnik Jul 10 '13 at 20:38
  • @JBNizet: I would, but this is the one which contains the most probable questions for OCJP exam. I know that's lame, but I need to learn java on fasttrack. (I'm a COBOL developer). – mankand007 Jul 10 '13 at 20:42

4 Answers4

2

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.

Community
  • 1
  • 1
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
  • 1
    No, this would also be bad code since after the try-catch, `d` may not have been initialized. The really proper thing in most cases would be to let the exception propagate. Yet another example of the misfeature called *checked exceptions*. – Marko Topolnik Jul 10 '13 at 20:44
  • Ya that what I would have done in case of serious coding, if the valid initialization of `d` is key to rest of my code. This code is just a dummy . – AllTooSir Jul 10 '13 at 20:47
  • It would be a better dummy if you had a `throw new RuntimeException(e)` instead of printing the stacktrace - people googling for answers tend to read not past the first working snippet of code... – Gyro Gearless Jul 10 '13 at 20:57
1

The parse method throws a checked exception, ParseException (it's not a RuntimeException), so it must be caught or else it's a compiler error.

rgettman
  • 176,041
  • 30
  • 275
  • 357
1

If the code in question finds itself:

  1. in a method which doesn't declare the checked ParseException, and
  2. outside of any try-catch block which would catch it,

then A will give a compiler error: Uncaught exception ParseException: must be caught or declared to be thrown.

However, if you literally replace //Insert correct code here with the code under C, and try to actually read the variable d after it, you'll get the error local variable may not have been initialized.

Not to mention the empty catch-block, and the funny semicolon after it...

In a word, this is very bad material you have to work with.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
-1

import java.util.Scanner;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class Main 
{
    public static final String FORMAT ="dd/MM/yyyy";
    
    public static void main(String[] args)         
    {
            Scanner sc=new Scanner(System.in);
            String date_input = sc.nextLine();
            Date d1;
            try
            {
                d1 = convertStringToDate(date_input);
                System.out.println(date_input+" is a valid date");
            }
            catch(ParseException e)
            {
                System.out.println(date_input+" is not a valid date");
            }
    }
    
    public static Date convertStringToDate(String str) throws ParseException
    {
        
            SimpleDateFormat df = new SimpleDateFormat(FORMAT);
            df.setLenient(false);
            Date d = df.parse(str);
            return d;
    }

}
  • Hey Sneha, I get you were trying to achieve to explain via the code. Great work with the code but a more concrete answer with like rather than taking the date via input, what you could have done is create few hard-coded dates and show how it throws an exception. – adnaan.zohran May 18 '21 at 16:53