-3
String from = "2019.03.03";
SimpleDateFormat fDate = new SimpleDateFormat("yyyy.MM.dd"); 
Date n = fDate.parse(from);

It has unhandled exception type ParseException "fDate.parse(from)" this line

How can I fix this code

mehdi
  • 340
  • 4
  • 17
Jokky
  • 63
  • 1
  • 9
  • 1
    Add a try-catch block arround this code. – Jens Jan 18 '21 at 06:08
  • The other thread uses Thread.sleep, not SimplateDateFormat#parse, but they both yield the same compiler error. – Tom Jan 18 '21 at 06:14
  • Oh, and please, use `DateTimeFormatter` and other classes from the `java.time` package, instead of `SimpleDateFormat` and `Date`, which are obsolete. [This is why](https://stackoverflow.com/questions/1969442/whats-wrong-with-java-date-time-api). – MC Emperor Jan 18 '21 at 10:38

1 Answers1

0

The error says we need to handle "if" a parse exception is thrown. To handle exception, we can use try-catch block, like this:

try {
    String from = "2019.03.03";
    SimpleDateFormat fDate = new SimpleDateFormat("yyyy.MM.dd"); 
    Date n = fDate.parse(from);
    System.out.println(n);  
} catch(ParseException ex) {
    ex.printStackTrace();
}
dyon048
  • 174
  • 4