Android Programming catch exception message

2.1k views Asked by At

I am writing a calculator program in Java using Android Studio.

I have a try/catch block in my program, with the catch block catching a NumberFormatException for invalid input.

} catch (NumberFormatException e) {

}

Without this try/catch block and I don't handle the exception of a user entering invalid input, a message pops up saying "Unfortunately, CalculatorApp has stopped" and the app closes.

With this exception, upon entering invalid input the app doesn't close (good!) but nothing happens when the user clicks he enter button.

How do I make it so a message pops up upon catching the exception?

3

There are 3 answers

0
jonhid On

Just put a toast message inside the catch block, like this ...

Toast toast1 = Toast.makeText(getApplicationContext(), "Invalid input",Toast.LENGTH_SHORT);

toast1.show();
0
Hasif Seyd On

In the catch block , you can display a Toast message When the exception occurs.

0
Rishabh Mahatha On
} catch (NumberFormatException e) {
 Toast.makeText(this, "Invalid Input", Toast.LENGTH_SHORT).show();

}

Use this it will show message to user. or if yo want to show the exception to user then use

} catch (NumberFormatException e) {
     Toast.makeText(this, "Invalid Input" +e, Toast.LENGTH_SHORT).show();

    }