0

I have two fields that i want to calculate. The program works fine if i put in numbers in both fields, but if i have one empty and presses my "buttonSubtract" (calc-button) it just shuts down with "application closed...". Why doesn´t the catch-clause catch the exception?

protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    buttonSubtract = (Button) findViewById(R.id.buttonsubtract);
    editTextNumber1 = (EditText) findViewById(R.id.textnumber1);
    editTextNumber2 = (EditText) findViewById(R.id.textnumber2);
    textSum = (TextView) findViewById(R.id.textViewSum);

    try
    buttonSubtract.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                if (editTextNumber1.getText().toString() == ""
                        || editTextNumber2.getText().toString() == "")
                {
                    textSum.setText("Put numbers in both fields");

                } else
                {
                    int sum = Integer.parseInt(editTextNumber1.getText()
                            .toString())
                            - Integer.parseInt(editTextNumber2.getText()
                                    .toString());
                    textSum.setText("sum: " + sum);
                }
            }
        });
    } catch (NumberFormatException e)
    {
        textSum.setText("Put numbers in both fields");
    }
4

4 回答 4

3

You can't catch exceptions that are thrown in an inner class from the outside. Move the try / catch block to the place where the NumberFormatException happens.

    buttonSubtract.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            String number1 = editTextNumber1.getText().toString().trim();
            String number2 = editTextNumber2.getText().toString().trim();
            if (!number1.isEmpty() && !number2.isEmpty()) {
                try {
                    int sum = Integer.parseInt(number1)
                            + Integer.parseInt(number2);
                    textSum.setText("sum: " + sum);
                    return;

                } catch (NumberFormatException e) {
                    // nothing to do
                }
            }
            textSum.setText("Put numbers in both fields");
        }
    });

The reason is simple: the code executed inside onClick is not called by you. It is called by the system once a click happens. Exceptions are only propagated to the caller.

It's simpler to see if you re-arrange the code a bit. Your code was equivalent to

OnClickListener someListener = getListener(); // this creates your implementation.
try {
    buttonSubtract.setOnClickListener(someListener);
} catch (NumberFormatException e) {
    // do stuff
}
于 2012-12-05T19:34:13.950 回答
2

Firstly, Always Compare String with .equals() method, == operator will check if two reference variables point/refer to the same Object:

if (editTextNumber1.getText().toString() == "" || editTextNumber2.getText().toString() == "")

should be if(editTextNumber1.getText().toString().equals("")||editTextNumber2.getText().toString().equals(""))

Or even better you can use String.isEmpty() to check if the string is empty.

Now, Regarding the actual problem:

Move your try/catch around the code which throw NumberFormatException for your catch to catch the exception.

   try {    
       int sum = Integer.parseInt(editTextNumber1.getText().toString())
                            - Integer.parseInt(editTextNumber2.getText().toString());
       textSum.setText("sum: " + sum);
   }
   catch(numberFormatException ex) {
       //do the stuff
     }
于 2012-12-05T19:30:22.717 回答
1

You only have a catch block for a NumberFormatException. Many other exceptions could be thrown before the block, or inside it. For instance, if any of the findViewById() methods you call at the beginning returns a null, any call to methods of that variable would throw a NullPointerException.

Check the logCat to see what exception is being thrown.

于 2012-12-05T19:30:34.053 回答
1

Exceptions thrown in your OnClickListener implementation will bot be caught by your try..catch statement because you are just creating it and setting as a listener, but not executing. It will be executed in other thread later, remove that and put your try..catch statement inside the onclick method.

Also you forgot a "{" after try, and you can't compare Strings with ==, it will compare if the variables has the same objects instead if they are equals. Use the equals(Object o) method instead, and to check if it's empty it's better to trim the string and use the isEmpty() method "sample".trim().isEmpty()

buttonSubtract.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            try
            {
                if (editTextNumber1.getText().toString().trim().isEmpty()
                        || editTextNumber2.getText().toString().trim().isEmpty())
                {
                    textSum.setText("Put numbers in both fields");

                } else
                {
                    int sum = Integer.parseInt(editTextNumber1.getText()
                            .toString())
                            - Integer.parseInt(editTextNumber2.getText()
                                    .toString());
                    textSum.setText("sum: " + sum);
                }

            } catch (NumberFormatException e)
            {
                textSum.setText("Put numbers in both fields");
            }
        }
    });
于 2012-12-05T19:42:13.560 回答