Android应用捕获不需要的异常

时间:2011-07-18 17:49:46

标签: android exception try-catch if-statement

我正在编写一个简单的应用程序,允许用户输入收入并扣除税款,然后将金额保存在文件中以备将来参考。问题是,如果我尝试在'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();
    }

1 个答案:

答案 0 :(得分:2)

完全可以预料到。这一行:

 Double incomeAmount = Double.parseDouble(postTax.getText().toString());
如果NumberFormatException编辑中输入的数字未解析为postTax

可以抛出double。底部catch是最接近捕获此异常的地方。

将此行(以及后续几行)放在try-catch块中稍微下方,以便在那里捕获异常。 (您可能希望将吐司消息更改为“无法处理税后价值”等内容。)

相关问题