我是Android编程新手并参加Coursera课程。在我的作业应用程序中,当用户未输入或输入错误的时间信息(HH:MM:SS)时,我试图捕获任何异常。
我的应用在用户出错后立即崩溃,而不是显示我的Toast消息或向Logcat显示日志消息。
SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
try {
Date dt = formatter.parse(MileTime);
Calendar cal = Calendar.getInstance();
cal.setTime(dt);
int hours = cal.get(Calendar.HOUR);
int minutes = cal.get(Calendar.MINUTE);
int seconds = cal.get(Calendar.SECOND);
int duration = 3600 * hours + 60 * minutes + seconds;
int steps_per_second = 3;
int running_rate = duration * steps_per_second;
//pleaseStop = false; //DouglasZare example, don't need this.
mHandler = new Handler(); // .os package class when importing
mLeftfoot = findViewById(R.id.leftfoot);
mRightfoot = findViewById(R.id.rightfoot);
mFootAnim = AnimationUtils.loadAnimation(this, R.anim.foot); //this looks to the foot.xml file for the animations
stepRecursive();
} catch (ParseException e) {
e.printStackTrace();
Log.e(TAG, "Invalid Mile Time Entry", e);
Toast.makeText(Assignment3MainActivity_V3_DouglasZare_AnimationCancel.this,
"Please Enter Valid Time Stamp HH:MM:SS", Toast.LENGTH_LONG).show();
}
错误日志位于:http://pastebin.com/By7FWxLk。
这个错误非常有意义并且是有意的。
Caused by: java.text.ParseException: Unparseable date: ""
我有什么办法来获取我的捕获语句来阻止这种情况?
答案 0 :(得分:4)
固定。啊。我将ParseException更改为Exception。它对我没有任何意义......我想要捕获的异常是IS ParseException。
catch (Exception e) {
e.printStackTrace();
Log.e(TAG, "Invalid Mile Time Entry", e);
Toast.makeText(Assignment3MainActivity_V3_DouglasZare_AnimationCancel.this,
"Please Enter Valid Time Stamp HH:MM:SS", Toast.LENGTH_LONG).show();
}
答案 1 :(得分:3)
原因是抛出的异常是IllegalStateException
而不是ParseException
。
如果查看崩溃日志的第5行,您会看到传递给您的异常是IllegalStateException
。这是因为捕获了ParseException,然后再重新抛出IllegalStateException
。
以下是多个catch块的示例。
try {
//some code that can throw an exception
} catch (IllegalStateException e) {
//catch the IllegalStateExeption
} catch (Exception e) {
//catch all the ones I didn't think of.
}