Android日期格式解析引发未处理的异常 [英] Android date format parse throwing an Unhandled Exception

查看:51
本文介绍了Android日期格式解析引发未处理的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将日期作为单个 string 存储在数据库中,格式为"2 15 2015"(大概是"M d yyyy"?).以下代码中的 strDate 包含获取日期的方法的返回值.我想解析日期,以便设置一个 datepicker .根据 Java字符串到日期的转换

I'm storing dates in a database as a single string in the format "2 15 2015" (presumably "M d yyyy"?). strDate in the code below contains the return value of a method that grabs the date. I want to parse the date so as to set a datepicker. Based on the examples in Java string to date conversion

我创建了以下代码来解析日期,但是在

I've created the following code for parsing the date, but am getting an "Unhandled Exception: java.text.ParseException" at

Date date = format.parse(strDate);

挠头.

Calendar mydate = new GregorianCalendar();
String strDate = datasource.get_Column_StrVal(dbData,
        MySQLiteHelper.dbFields.COLUMN_SPECIAL_DAYS_DATE);
SimpleDateFormat  format = new SimpleDateFormat("M d yyyy", Locale.ENGLISH);
Date date = format.parse(strDate);
mydate.setTime(date);

推荐答案

由于没有处理 parse 方法的 ParseException ,因此收到了编译时错误.抛出.这是必需的,因为 ParseException 不是运行时异常(由于它直接从 java.lang.Exception 扩展而来,因此是受检查的异常).

You are getting this compile-time error because you are not handling the ParseException that the parse method throws. This is necessary because ParseException is not a runtime exception (it is a checked exception since it extends directly from java.lang.Exception).

您需要在代码周围加上try/catch来处理异常,像这样:

You need to surround your code with try/catch to handle the exception, like this :

try {
    SimpleDateFormat  format = new SimpleDateFormat("M d yyyy", Locale.ENGLISH);
    Date date = format.parse(strDate);
    mydate.setTime(date);
} catch (ParseException e) {
    //handle exception
}

这篇关于Android日期格式解析引发未处理的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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