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

¿Cómo hacer bucles en el programa después de lanzar una excepción en 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 then call the method again.

Example

In the following example, we have a container that includes5elements 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);
      System.out.println("Error: Ha elegido una posición que no está en el array: INTENTE DE NUEVO");
         catch(ArithmeticException e) {
         getInputs(arr);
      }
         System.out.println("Error: El denominador no debe ser cero: INTENTE DE NUEVO");
         getInputs(arr);
      }
   }
   public static void main(String [] args) {
      LoopBack obj = new LoopBack();
      System.out.println("Array: "+Arrays.toString(obj.arr));
      getInputs(obj.arr);
   }
}

Resultado de salida

Array: [10, 20, 30, 2, 0, 8]
Elija el numerador y el denominador (no 0) de este array (ingrese posiciones de 0 a 5)
14
24
Error: Ha elegido una posición que no está en el array: INTENTE DE NUEVO
Elija el numerador y el denominador (no 0) de este array (ingrese posiciones de 0 a 5)
3
4
Error: El denominador no debe ser cero: INTENTE DE NUEVO
Elija el numerador y el denominador (no 0) de este array (ingrese posiciones de 0 a 5)
0
3
Resultado de 10/2: 5