কখনো কখনো জাভাতে একটি এক্সেপশন রি-থ্রো করা প্রয়োজন হতে পারে। যদি একটি catch block ক্যাচ করা নির্দিষ্ট এক্সেপশনটি হ্যান্ডেল না করতে পারে, তবে আমরা এক্সেপশনটি রি-থ্রো করতে পারি। রি-থ্রো এক্সপ্রেশন মূলভাবে থ্রো করা অবজেক্টকে আবার থ্রো করে।
কারণ এক্সেপশনটি ইতিমধ্যে ক্যাচ হয়েছে সেই স্কোপে যেখানে রি-থ্রো এক্সপ্রেশন ঘটেছে, এটি পরবর্তী enclosing try ব্লকে বের হয়ে যাওয়ায় রি-থ্রো হয়। তাই, এটি সেই স্কোপের catch blocks দ্বারা হ্যান্ডেল করা যায় না যেখানে রি-থ্রো এক্সপ্রেশন ঘটেছে। enclosing try ব্লকের যেকোনো catch blocks-এর এটিকে ক্যাচ করার সুযোগ থাকে।
সিনট্যাক্স
catch(Exception e) {
System.out.println("An exception was thrown");
throw e;
}
উদাহরণ
public class RethrowException {
public static void test1() throws Exception {
System.out.println("The Exception in test1() method");
throw new Exception("thrown from test1() method");
}
public static void test2() throws Throwable {
try {
test1();
} catch(Exception e) {
System.out.println("Inside test2() method");
throw e;
}
}
public static void main(String[] args) throws Throwable {
try {
test2();
} catch(Exception e) {
System.out.println("Caught in main");
}
}
}
আউটপুট
The Exception in test1() method Inside test2() method Caught in main