user650309
user650309

Reputation: 2899

Android application catching unwanted exception

I'm writing a simple app which allows a user to enter their income and it deducts tax, then saves the amount in a file for future reference. The problem is that if I try to enter anything in the 'postTax' editText, it will throw the bottom exception. I'm obviously doing something stupid with my logic but can anyone see the problem?

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

Upvotes: 0

Views: 354

Answers (1)

Xion
Xion

Reputation: 22770

It's totally expected. The line:

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

can throw NumberFormatException if number entered in postTax edit doesn't parse to double. The bottom catch is the closest one to capture this exception.

Put this line (along with few subsequent ones) inside the try-catch block a little below to have the exception caught there. (You will likely want to change the toast message though, into something like "Failed to process post tax value").

Upvotes: 2

Related Questions