我正在编写一个约会程序,该程序允许用户输入约会日期,描述和约会类型。一切正常,直到他们选择“打印范围”以打印日期范围,当他们选择执行此操作时,它告诉他们输入开始日期和结束日期,然后程序从这些日期之间提取所有约会并将它们显示在输出框中。
这是我在打印范围时遇到的错误:
AppointmentNew.java:68: unreported exception java.text.ParseException; must be caught or declared to be thrown
Date lowDate = sdf.parse(stdin.nextLine());
^
AppointmentNew.java:70: unreported exception java.text.ParseException; must be caught or declared to be thrown
Date highDate = sdf.parse(stdin.nextLine());
^
AppointmentNew.java:77: unreported exception java.text.ParseException; must be caught or declared to be thrown
Date newCurrentDate = sdf.parse(currentDate);
我想我应该做一个try / catch块,但是我不确定该怎么做,并且想知道是否有人可以为我提供解决这些错误的答案或示例。
这是我认为解析错误发生的一些代码:
import java.util.*;
import java.text.SimpleDateFormat;
import java.util.Date;
public class AppointmentNew
{
public static void main (String[] args) throws Exception
{
if (choiceNum == 2)
{
System.out.print("\n\n\tEnter START Date in mm/dd/yyyy format: ");
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date lowDate = sdf.parse(stdin.nextLine());
System.out.print("\n\n\tEnter END Date in mm/dd/yyyy format: ");
Date highDate = sdf.parse(stdin.nextLine());
for(int i = 0; i < list.size(); i++)
{
int dateSpot = list.get(i).indexOf(" ");
String currentDate = list.get(i);
currentDate.substring(0, dateSpot);
Date newCurrentDate = sdf.parse(currentDate);
if (newCurrentDate.compareTo(lowDate) >= 0 && newCurrentDate.compareTo(highDate) <= 0)
{
System.out.println("\n\t" + list.get(i));
}
}
}
解析异常是已检查的异常,因此您必须进行处理。通过掷球或尝试挡块。
public static void main (String[] args)
应该
public static void main (String[] args) throws ParseException
或者在try catch块中
try {
//All your parse Operations
} catch (ParseException e) {
//Handle exception here, most of the time you will just log it.
e.printStackTrace();
}