[Android] 使用try catch處理使用者輸入錯誤

try catch 可以針對例外事件做處理,因此若使用者輸入有誤的格式造成exception,就可以利用try{
主流程
}
catch(Exception obj){
例外處理
}

程式碼如下,若輸入不是數字,抓到exception後提示輸入Number。
try{
         ...
     double height = Double.parseDouble(edit_text_height.getText().toString())/100;
     double weight = Double.parseDouble(edit_text_weight.getText().toString());
        ....
}catch(Exception obj){
Toast.makeText(MainActivity.this, "Please input Number", Toast.LENGTH_SHORT).show();
}

沒有留言:

張貼留言