예외가 catch 블록에 캐시되면 throw 키워드(예외 개체를 throw하는 데 사용됨)를 사용하여 예외를 다시 throw할 수 있습니다.
예외를 다시 던지는 동안 −
로 조정하지 않고 그대로 동일한 예외를 던질 수 있습니다.try { int result = (arr[a])/(arr[b]); System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result); } catch(ArithmeticException e) { throw e; }
또는 새 예외 내에서 래핑하고 던집니다. 캐시된 예외를 다른 예외 내에서 래핑하고 throw하는 경우 이를 예외 연결 또는 예외 래핑이라고 합니다. 이렇게 하면 예외를 조정하여 추상화를 유지하는 더 높은 수준의 예외를 throw할 수 있습니다.
try { int result = (arr[a])/(arr[b]); System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result); } catch(ArrayIndexOutOfBoundsException e) { throw new IndexOutOfBoundsException(); }
예시
다음 Java 예제에서 demoMethod()의 코드는 ArrayIndexOutOfBoundsException과 ArithmeticException을 던질 수 있습니다. 우리는 두 개의 다른 catch 블록에서 이 두 가지 예외를 포착하고 있습니다.
catch 블록에서 상위 예외와 다른 예외를 직접 래핑하여 두 예외를 모두 다시 throw합니다.
import java.util.Arrays; import java.util.Scanner; public class RethrowExample { public void demoMethod() { Scanner sc = new Scanner(System.in); int[] arr = {10, 20, 30, 2, 0, 8}; System.out.println("Array: "+Arrays.toString(arr)); 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) { throw new IndexOutOfBoundsException(); } catch(ArithmeticException e) { throw e; } } public static void main(String [] args) { new RethrowExample().demoMethod(); } }
출력1
Array: [10, 20, 30, 2, 0, 8] Choose numerator and denominator(not 0) from this array (enter positions 0 to 5) 0 4 Exception in thread "main" java.lang.ArithmeticException: / by zero at myPackage.RethrowExample.demoMethod(RethrowExample.java:16) at myPackage.RethrowExample.main(RethrowExample.java:25)에서
출력2
Array: [10, 20, 30, 2, 0, 8] Choose numerator and denominator(not 0) from this array (enter positions 0 to 5) 124 5 Exception in thread "main" java.lang.IndexOutOfBoundsException at myPackage.RethrowExample.demoMethod(RethrowExample.java:17) at myPackage.RethrowExample.main(RethrowExample.java:23)의 RethrowExample.demoMethod(RethrowExample.java:17)