Consider the following code and show how you could use exceptions to terminate t
ID: 3861781 • Letter: C
Question
Consider the following code and show how you could use exceptions to terminate the program gracefully in the event of a runtime error. There are at least two potential runtime exceptions that might occur in the code below and you should notify the user as to which one has occurred. Do NOT rewrite the code, just be creative and show what needs to be add/changed. Scanner keyb = new Scanner (System in); double array[] = new double [10]; String continue = "yes"; while (continue -equals ("yes")) {System. out. print ("Enter an index:"); int i = keyb_nextInt (); System. out. println ("Enter a value:"); double val = keyb. nextDouble ();//put value into the array at position i array[i] = val; System. out. print ("Do you want to enter more values?:"); keyb. nextLine ();//eat the new line continue - keyb. nextLine();}Explanation / Answer
The two potential runtime exceptions that might occur while running the code are:
1. InputMismatchException
Scanner class throws this exception while value read from user cannot be converted into respective variable data type.
Statements that might rise these kind of exceptions are:
(a) int i = keyb.nextInt()
(b) double val = keyb.nextDouble();
2. ArrayIndexOutOfBoundsException
Double Array by name array is declared of size 10. If user enters value <0 or >9 for i value, then these kind of exceptions are raised.
Statement that might rise these kind of exceptions are:
(a) array[i] = val;
If value for variable i is less than 0 or greater than 9, ArrayIndexOutOfBoundsException is raised
___________________________________________________________________________________________________________________________
Place the entire code in try block and add appropriate exception handlers to handles the exceptions that might raise for terminating the program gracefully.
try
{
/* Your entire code goes here */
}
exception(ArrayIndexOutOfBoundsException ex)
{
System.out.println(" Error!!! Trying to access invalid array index... Please check ");
}
exception(InputMismatchException)
{
System.out.println(" Error!!! Trying to store invalid value... Please check ");
}
exception(Exception ex)
{
//Handles remaining all kind of errors
System.out.println(ex);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.