2011-07-18 24 views
0

我正在寫一個簡單的應用程序,它允許用戶輸入他們的收入和扣除它的稅收,然後將其保存以供將來參考文件的數量。問題是,如果我嘗試在'postTax'editText中輸入任何內容,它會拋出最後一個異常。我顯然是在用我的邏輯做一些愚蠢的事情,但是誰能看到這個問題?Android應用程序捕獲不必要的異常

public void onClick(View v) { 
    // TODO Auto-generated method stub 
    try { 

     if (preTax !=null){ 

      Double incomeAmount = Double.parseDouble(preTax.getText().toString()); 
      incomeAmount = incomeAmount - (0.2 *incomeAmount);  
      Double incomeRounded = Round(incomeAmount); 
      Toast.makeText(v.getContext(), "Your income minus tax = "+incomeRounded, Toast.LENGTH_LONG).show(); 
      String storeIncome = Double.toString(incomeRounded); 

      try{ 
       FileOutputStream fos = openFileOutput("income", Context.MODE_PRIVATE); 
       OutputStreamWriter osw = new OutputStreamWriter(fos); 
       osw.write(storeIncome); 

       osw.flush(); 
       osw.close(); 

      } catch(Exception e){ 
       Toast.makeText(this, "Error writing to file", Toast.LENGTH_LONG).show(); 
      } 
     } 

     else if (postTax!=null){ 

      Double incomeAmount = Double.parseDouble(postTax.getText().toString()); 
      Double incomeRounded = Round(incomeAmount); 
      Toast.makeText(v.getContext(), "Your income is: "+ incomeRounded, Toast.LENGTH_LONG).show(); 
      String storeIncome = Double.toString(incomeRounded); 


      try{ 
       FileOutputStream fos = openFileOutput("income", Context.MODE_PRIVATE); 
       OutputStreamWriter osw = new OutputStreamWriter(fos); 

       osw.write(storeIncome); 
       osw.flush(); 
       osw.close(); 

      } catch(Exception e){ 
       Toast.makeText(this, "Error writing to file", Toast.LENGTH_LONG).show(); 
      } 
     } 

    } catch (Exception e){ 
     Toast.makeText(v.getContext(), "Please fill in the relevant catagories", Toast.LENGTH_LONG).show(); 
    } 

回答

2

這是完全預期的。行:

Double incomeAmount = Double.parseDouble(postTax.getText().toString()); 

可以拋出NumberFormatException如果數postTax編輯進入不分析到double。底部的catch是捕獲此異常的最接近的一個。

把這一行(有一些後續的放在一起)的try-catch塊稍低於有異常捕獲有內部。 (儘管如此,您可能希望更改Toast消息,例如「無法處理稅後價值」)。

+0

啊!你是對的。我不明白這是爲什麼造成但是一個NumberFormatException異常,我輸入的數據是相同的稅前和不拋出異常? – user650309

+0

通過的邏輯你的'if'構建體,所述'postTax'部分將不會被即使有一個'preTax'變量集(其,我假設,是參考一些'EditText')執行。考慮到這一點,這可能是您的代碼意外/錯誤行爲的主要原因。 – Xion

相關問題