2011-07-18 26 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

相关问题