为什么在使用SimpleDateFormat时出现ParseException [英] why the ParseException appears when use SimpleDateFormat

查看:538
本文介绍了为什么在使用SimpleDateFormat时出现ParseException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用eclipse编写了以下代码:

I wrote the code below with 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

or add throws ParseException at the beginning of main method

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?

They all work well... What's wrong with my code? I use the method printStackTrace() at the catch block, but why can't I see the ParseException?

推荐答案

这与您实际上获得异常无关.但是您的String可能格式错误(不是这样).在这种情况下,您将获得例外.

This is not about you actually getting an exception. But it's possible that your String is in the wrong format (which it is not). In that case you would get an exception.

因此,编译器希望您处理该异常.您要么将其重新扔掉要么将其抓住.但是:您的代码实际上不会得到异常.以防万一有例外.

So the compiler wants you to handle that exception. You either have to rethrow it or catch it. BUT: You won't actually get the exception with your code. It's just in case there ever is an exception.

这篇关于为什么在使用SimpleDateFormat时出现ParseException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆