How to loop the program after an exception is thrown in java?

Java 8Object Oriented ProgrammingProgramming

Read the inputs and perform the required calculations within a method. Keep the code that causes exception in try block and catch all the possible exceptions in catch block(s). In each catch block display the respective message and call the method again.

Example

In the following example we have an array with 5 elements, we are accepting two integers from user representing positions in the array and performing division operation with them, if the integer entered representing the positions is more than 5 (length of the exception) an ArrayIndexOutOfBoundsException occurs and, if the position chosen for denominator is 4 which is 0 an ArithmeticException occurs.

We are reading values and calculating the result in a static method. We are catching these two exceptions in two catch blocks and in each block we are invoking the method after displaying the respective message.

import java.util.Arrays;
import java.util.Scanner;
public class LoopBack {
   int[] arr = {10, 20, 30, 2, 0, 8};
   public static void getInputs(int[] arr){
      Scanner sc = new Scanner(System.in);
      System.out.println("Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)");
      int a = sc.nextInt();
      int b = sc.nextInt();
      try {
         int result = (arr[a])/(arr[b]);
         System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result);
      }catch(ArrayIndexOutOfBoundsException e) {
         System.out.println("Error: You have chosen position which is not in the array: TRY AGAIN");
         getInputs(arr);
      }catch(ArithmeticException e) {
         System.out.println("Error: Denominator must not be zero: TRY AGAIN");
         getInputs(arr);
      }
   }
   public static void main(String [] args) {
      LoopBack obj = new LoopBack();
      System.out.println("Array: "+Arrays.toString(obj.arr));
      getInputs(obj.arr);
   }
}

Output

Array: [10, 20, 30, 2, 0, 8]
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
14
24
Error: You have chosen position which is not in the array: TRY AGAIN
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
3
4
Error: Denominator must not be zero: TRY AGAIN
Choose numerator and denominator(not 0) from this array (enter positions 0 to 5)
0
3
Result of 10/2: 5
raja
Published on 06-Aug-2019 15:03:47
Advertisements