我尝试在java上将字符串转换为日期。我阅读并尝试了这个网站"Java Date and Calendar examples"的例子,但我仍然无法编译和运行它。
这是我的代码。
package javaapplication5;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
public class JavaApplication5 {
public static void main(String[] args) {
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
String dateInString = "31-08-1982 10:20:56";
Date date = sdf.parse(dateInString);
System.out.println(date);
}
}
我收到了这个错误。
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.text.ParseException; must be caught or declared to be thrown
我错过了什么或做错了什么?谢谢你的帮助。
答案 0 :(得分:1)
问题是java.text.ParseException
是checked exception
已检查的异常是一种异常,必须在抛出它的方法中捕获或声明
所以......你可以在throws
列表
public static void main(String[] args) throws ParseException {
/* ... */
}
或者应该妥善处理它
public static void main(String[] args) {
try {
Date date = sdf.parse(dateInString);
} catch (ParseException e) {
// do proper thing here like try another
// format or log/rethrow/wrap exception
}
}
答案 1 :(得分:0)
只需在try catch块中添加代码即可。
try {
//parse code
}
catch (ParseException e) {
//handling exceptions
}
答案 2 :(得分:0)
尝试将所有代码放入try / catch块
try{
// your code here.
}catch(Exception e){
e.printStackTrace();
}
答案 3 :(得分:0)
像这样添加try-catch
块:
try
{
//...Code.... Mainly below:
Date date = sdf.parse(dateInString);
} catch (ParseException e)
//Or any superclass, such as RuntimeException,
//although use superclass ONLY to be generic, not otherwise, such as
//if you want to handle all exceptions the same way.
{
//...Handler Code...
}
答案 4 :(得分:0)
SimpleDateFormat sdf = new SimpleDateFormat("dd-M-yyyy hh:mm:ss");
String dateInString = "31-08-1982 10:20:56";
Date date = null;
try {
date = sdf.parse(dateInString);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(date);