I wrote the code below with eclipse:
String d = "2014-6-1 21:05:36";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date =sdf.parse(d);
System.out.print(date);
and the line 4 throws an Unhandled exception type ParseException.
But if I write:
try {
String d = "2014-6-1 21:05:36";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date =sdf.parse(d);
System.out.print(date);
} catch(ParseException e) {
e.printStackTrace();
System.out.print("you get the ParseException");
}
or add throws ParseException
at the beginning of main method
public static void main(String[] args) throws ParseException {
String d = "2014-6-1 21:05:36";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date =sdf.parse(d);
System.out.print(date);
}
They all work well... What's wrong with my code? I use the method printStackTrace()
at the catch block, but why can't I see the ParseException?
This is not about you actually getting an exception. But it's possible that your String is in the wrong format (which it is not). In that case you would get an exception.
So the compiler wants you to handle that exception. You either have to rethrow it or catch it. BUT: You won't actually get the exception with your code. It's just in case there ever is an exception.