Reference no: EM132013064
How would you code the following in Java when given the coding below?
-Organize the code capable of throwing an exception of type ParseException as a try block.
-Include a catch block to handle a ParseException error thown by the try block.
-Include a hard-coded error that results in a ParseException to prove that the code can catch and handle this type of exception.
public static void main(String[] args){
// The getInstance() method returns a Calendar object whose calendar fields have been initialized with the current date and time.
Calendar calendar = Calendar.getInstance(); {
//LINE 1. BEGIN THE TRY BLOCK.
String str_date="01-Nov-17"; // Declare a string that we will use later to format a date like this: ##-XXX-##
DateFormat formatter; // Declare an object of type DateFormat so that we can call its parse() method later
Date myFormattedDate; // Declare a variable of type Date to hold the formatted date
formatter = new SimpleDateFormat("dd-MMM-yy"); // Assign a specific date format to the formatter variable
// The given date is taken as a string that is converted into a date type by using
// the parse() method
myFormattedDate = (Date)formatter.parse(str_date); // setting up the format
System.out.println("The formatted date is " + myFormattedDate);
System.out.println("Today is " +calendar.getTime() );
}
//LINE 2. DD THE CATCH BLOCK TO CATCH EXCEPTIONS OF TYPE ParseException (TO HANDLE EXCEPTION, SIMPLY PRINT THE EXCEPTION)