Android应用程序捕获不必要的异常



我正在编写一个简单的应用程序,允许用户输入他们的收入并扣除税款,然后将金额保存在文件中以备将来参考。问题是,如果我尝试在'postTax' editText中输入任何东西,它将抛出底部异常。显然我的逻辑出了问题但有人能看出问题所在吗?

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();
    }

完全在意料之中。线:

 Double incomeAmount = Double.parseDouble(postTax.getText().toString());
如果在postTax编辑中输入的数字不能解析到double

将抛出NumberFormatException。底部的catch是最接近捕获此异常的。

将这行(以及随后的几行)放在try-catch块的下面一点,以便在那里捕获异常。(不过,您可能希望将toast消息更改为"未能处理税后价值"之类的内容)。

最新更新