때로는 Java에서 예외를 다시 throw해야 할 수도 있습니다. catch 블록이 포착한 특정 예외를 처리할 수 없는 경우 예외를 다시 throw할 수 있습니다. rethrow 표현식은 원래 던진 개체가 rethrow되도록 합니다.
예외는 rethrow 표현식이 발생하는 범위에서 이미 포착되었기 때문에 다음 바깥쪽 try 블록으로 다시 throw됩니다. 따라서 rethrow 식이 발생한 범위에서 catch 블록으로 처리할 수 없습니다. 둘러싸는 try 블록에 대한 모든 catch 블록에는 예외를 catch할 기회가 있습니다.
구문
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