why the ParseException appears when use SimpleDateFormat [duplicate]

自闭症网瘾萝莉.ら 提交于 2019-12-12 03:04:38

问题


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);

and the line 4 throws an Unhandled exception type ParseException.

But if I write:

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 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);
}

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?


回答1:


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.




回答2:


In any IDE (Integrated Development Environment), editor show the compile type error that will be unresolved at compile-time.

What you are observing the behavior of IDE in your case, at sdf.parse(d);means it can throw an parse exception at runtime, So you have to handle it accordinly. Otherwise program will be crashed.

In second code snippet of yours, It will catch an parse exception when occured and show you the exception e.printStackTrace(); for your record and code will not crash, i.e. exit(0) or exit(1) with error, more

While in last code snippet of yours, method is been decleared that it may throw an exception, So if it called from any other source, this should be handled, say try catch.

You can use any of the two solution, its just your choice.

more

following is the method signature in SimpleDateFormat

public Date parse(String source) throws ParseException

So this throws indicates that when this method is been called this must be handled



来源:https://stackoverflow.com/questions/41058499/why-the-parseexception-appears-when-use-simpledateformat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!