簡體   English   中英

Android-Try Catch未捕獲異常,並且未顯示我的吐司消息

[英]Android - Try Catch is not catching the exception and it's not displaying my toast message

我是Android編程的新手,參加了Coursera課程。 在我的作業應用中,當用戶未輸入或輸入錯誤的時間信息(HH:MM:SS)時,我試圖捕獲所有異常。

我的應用程序在用戶錯誤后立即崩潰,而不是顯示我的Toast消息或向Logcat顯示Log消息。

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: ""

我有什么辦法來獲取我的catch語句以防止這種情況發生?

固定。 啊。 我將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();
    }

原因是拋出的異常是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.
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM