Answer:
Here is the program that demonstrates the use of JAVA exception:
import java.util.Scanner; //to accept input from user
public class Main { //class name
public static void main(String[] args) { //start of main method
Scanner input = new java.util.Scanner(System.in); //creates Scanner class object to accept input from user
int number1 = 0; //stores the first integer value
int number2 = 0; //stores the second integer value
while(true) { //keeps looping until user enters integer value
System.out.println("Enter 2 integers to perform addition: "); //prompts user to enter two integer values
try { //defines a chunk of code to check for errors
number1 = input.nextInt(); //reads input integer 1
number2 = input.nextInt(); //reads input integer 2
break; }
catch (java.util.InputMismatchException e) { // defines a code chunk to execute if an error occurs in the try code chunk
System.out.println("Input must be an integer "); //displays this message if user enters anything other than an integer value
input.nextLine(); } } // reads input from user again until user enters both integer type values
System.out.println("The sum is: " + (number1+number2)); } } //if user enters 2 integers then computes and displays the sum of two integer values
Step-by-step explanation:
The program uses InputMismatchException exception and asks the user to input two integers and computes the sum of two integers if user enters integers otherwise an exception InputMismatchException is thrown and a error message Input must be an integer is displayed to the user if they input a string of letters instead o f integer values. Here while loop is used which keeps executing until user enters both the integer values. After the user enters correct values, the sum of the two integers are computed and result is displayed on output screen. The screenshot of program and its output is attached.
Another program asks the user to input an integer and the program executes correctly if they enter an integer but exception InputMismatchException is thrown with an error message that is is displayed to the user if they input a string of letters. Here is the program:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new java.util.Scanner(System.in);
int number1 = 0;
while(true) {
System.out.println("Enter an integer value: ");
try {
number1 = input.nextInt();
break; }
catch (java.util.InputMismatchException e) {
System.out.println("Input must be an integer ");
input.nextLine(); } }
System.out.println("The program executed correctly!"); } }