Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Re-throwing exceptions trong Java có nghĩa là gì?


Khi exception bị bắt trong catch block, có thể re-throw (ném lại) bằng từ khóa throw (dùng để ném object exception).

Khi re-throw, có thể ném chính exception đó không chỉnh sửa:

try {    int result = (arr[a])/(arr[b]);    System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result); } catch(ArithmeticException e) {    throw e; }

Hoặc wrap trong exception mới và ném. Khi wrap exception bắt được trong exception khác rồi ném, gọi là exception chaining/wrapping, giúp ném exception cấp cao hơn giữ abstraction.

try {    int result = (arr[a])/(arr[b]);    System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result); } catch(ArrayIndexOutOfBoundsException e) {    throw new IndexOutOfBoundsException(); }

Ví dụ

Trong ví dụ Java sau, code trong demoMethod() có thể ném ArrayIndexOutOfBoundsException và ArithmeticException. Bắt hai exception này ở hai catch block khác nhau.

Trong catch block, re-throw cả hai: một wrap trong exception cấp cao, một ném trực tiếp.

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();    } }

Kết quả 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)

Kết quả 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)