Java Reference
In-Depth Information
to rethrow to hide the location of the original exception. The following snippet of code shows how to rethrow an
exception by hiding the location of the original exception:
try {
// Code that might throw MyException
}
catch(MyException e) {
// Re-package the stack frames in the exception object
e.fillInStackTrace();
// Rethrow the same exception
throw e;
}
Listing 9-12 demonstrates how to rethrow an exception by hiding the location of the original exception. The
MyException is thrown inside the m2() method. The m1() method catches the exception, refills the stack trace, and
rethrows it. The main() method receives the exception as if the exception was thrown inside m1() , not inside m2() .
Listing 9-12. Rethrowing an Exception to Hide the Location of the Original Exception
// RethrowTest.java
package com.jdojo.exception;
public class RethrowTest {
public static void main(String[] args) {
try {
m1();
}
catch(MyException e) {
// Print the stack trace
e.printStackTrace();
}
}
public static void m1() throws MyException {
try {
m2();
}
catch(MyException e) {
e.fillInStackTrace();
throw e;
}
}
public static void m2() throws MyException {
throw new MyException("An error has occurred.");
}
}
com.jdojo.exception.MyException: An error has occurred.
at com.jdojo.exception.RethrowTest.m1(RethrowTest.java:20)
at com.jdojo.exception.RethrowTest.main(RethrowTest.java:7)
 
Search WWH ::




Custom Search