जब किसी अपवाद को कैच ब्लॉक में पकड़ा जाता है, तो आप throw कीवर्ड का उपयोग करके इसे पुनः फेंक सकते हैं (जिसका उपयोग अपवाद ऑब्जेक्ट्स को फेंकने के लिए किया जाता है)।
अपवादों को पुनः फेंकते समय आप बिना समायोजित किए उसी अपवाद को वैसे ही फेंक सकते हैं -
try { int result = (arr[a])/(arr[b]); System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result); } catch(ArithmeticException e) { throw e; } या, इसे एक नए अपवाद के भीतर लपेटकर फेंक दें। जब आप किसी पकड़े गए अपवाद को किसी अन्य अपवाद के भीतर लपेटते हैं और उसे फेंकते हैं, तो इसे अपवाद चेनिंग या अपवाद रैपिंग के रूप में जाना जाता है, ऐसा करके आप अपने अपवाद को समायोजित कर सकते हैं, अमूर्तता बनाए रखते हुए उच्च स्तर का अपवाद फेंक सकते हैं।
try { int result = (arr[a])/(arr[b]); System.out.println("Result of "+arr[a]+"/"+arr[b]+": "+result); } catch(ArrayIndexOutOfBoundsException e) { throw new IndexOutOfBoundsException(); } उदाहरण
निम्नलिखित जावा उदाहरण में हमारा कोड demoMethod() ArrayIndexOutOfBoundsException और ArithmeticException फेंक सकता है। हम इन दो अपवादों को दो अलग-अलग कैच ब्लॉक्स में पकड़ रहे हैं।
कैच ब्लॉक्स में, हम दोनों अपवादों को पुनः फेंक रहे हैं एक को उच्च अपवाद के भीतर लपेटकर और दूसरे को सीधे।
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)