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

Java에서 예외를 발생시운 후 프로그램을 반복적으로 어떻게 처리할 수 있습니까?

Read input and perform the required calculations in the method. The code that will cause an exception is retained 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 container containing5an element 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 entered 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);
   }
}

출력 결과

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
좋아할 만한 것