English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

How to loop a program after throwing an exception in Java?

Read input and perform the required calculations in the method. Code that will cause an exception is kept in the try block, and all possible exceptions are caught in the catch block. Display the corresponding message in each catch block, and call the method again.

Example

In the following example, we have a containing5elements array, we accept two integers from the user to represent the position of the array, and perform division operations on them, if the integer representing the position is greater than5(the length of the exception), an ArrayIndexOutOfBoundsException will occur, and if the position chosen for the denominator is4(i.e., 0), an ArithmeticException will occur.

We are reading values and calculating the result with a static method. We catch these two exceptions in two catch blocks, and in each block, we call this method after displaying the corresponding 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 Result

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