我用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");
}
or add throws ParseException
在 main 方法的开头
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);
}
它们都工作得很好...我的代码有什么问题吗?我用的方法printStackTrace()
在 catch 块中,但为什么我看不到 ParseException?
这并不是说你实际上得到了例外。但您的字符串可能格式错误(事实并非如此)。在这种情况下,你会得到一个例外。
所以编译器希望你处理这个异常。你要么必须重新扔它,要么接住它。但是:您的代码实际上不会得到异常。以防万一有例外。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)