【发布时间】:2016-12-09 10:40:42
【问题描述】:
我用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);
第 4 行抛出 Unhandled exception type ParseException.
但如果我写:
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");
}
或者在main方法的开头加上throws ParseException
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);
}
它们都运行良好...我的代码有什么问题?我在 catch 块中使用了 printStackTrace() 方法,但是为什么我看不到 ParseException?
【问题讨论】:
-
它告诉您 SimpleDateFormat 的解析表明它可能会抛出该异常。这并不意味着它做到了。编译器希望您处理它,或者通过将您的方法标记为可能是此异常的来源来确认它是可能的。
-
您在案例 2 中使用了不同的格式,即您打印异常的格式。
-
我很确定你的第三段摘录没有效果很好。
标签: java parseexception