Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธี Rethrow Exception ใน Java

บางครั้งเราอาจต้อง rethrow exception ใน Java หาก catch block ไม่สามารถจัดการ exception ที่จับได้ เราสามารถ rethrow exception นั้นได้ Rethrow expression ทำให้ originally thrown object ถูก rethrown

เนื่องจาก exception ถูกจับแล้วที่ scope ที่ rethrow expression เกิดขึ้น มันจะถูก rethrown ออกไปยัง try block ที่ล้อมรอบ (enclosing) ถัดไป ดังนั้น จึงไม่สามารถจัดการโดย catch blocks ที่ scope ที่ rethrow expression เกิดขึ้นได้ Catch blocks ใดๆ สำหรับ enclosing try block จะมีโอกาสจับ exception ได้

Syntax

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