java - 为什么使用 SimpleDateFormat 时出现 ParseException

标签 java parseexception

我用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");
}

或添加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 block 中,但为什么我看不到 ParseException?

最佳答案

这并不是说你实际上得到了异常。但您的字符串可能格式错误(事实并非如此)。在这种情况下,您将得到一个异常(exception)。

因此编译器希望您处理该异常。你要么必须重新扔它,要么接住它。但是:您的代码实际上不会得到异常。这是为了以防万一出现异常。

关于java - 为什么使用 SimpleDateFormat 时出现 ParseException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41058499/

相关文章:

java - java.text.DateFormat 中的 ParseException

java - Android 上的时间解析问题

java - 更改包名称后意外的顶级异常

java - 从 addMouseListener 恢复 getSelectedValue

java - 字符串换行导致错误

java - Gradle 任务在 GitLab CI main 方法上失败,找不到

java - org.triten.bp.format.DateTimeParseException : Text '2018-07-22T14:00:00-03:00' could not be parsed at index 19

Java - 一个文件中的代码和另一文件中的设计(无法识别的 actionPerformed 事件)

java - SQL异常 : Could not retrieve transation read-only status server

java - ParseException Java