2015-09-07 11:44:36 -06:00
|
|
|
// exceptions/RethrowNew.java
|
2016-12-30 17:23:13 -08:00
|
|
|
// (c)2017 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2016-01-25 18:05:55 -08:00
|
|
|
// Rethrow a different object from the one you caught
|
2015-06-15 17:47:35 -07:00
|
|
|
|
|
|
|
class OneException extends Exception {
|
|
|
|
public OneException(String s) { super(s); }
|
|
|
|
}
|
|
|
|
|
|
|
|
class TwoException extends Exception {
|
|
|
|
public TwoException(String s) { super(s); }
|
|
|
|
}
|
|
|
|
|
|
|
|
public class RethrowNew {
|
|
|
|
public static void f() throws OneException {
|
2015-12-15 11:47:04 -08:00
|
|
|
System.out.println(
|
|
|
|
"originating the exception in f()");
|
2015-06-15 17:47:35 -07:00
|
|
|
throw new OneException("thrown from f()");
|
|
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
|
|
try {
|
|
|
|
try {
|
|
|
|
f();
|
|
|
|
} catch(OneException e) {
|
|
|
|
System.out.println(
|
|
|
|
"Caught in inner try, e.printStackTrace()");
|
|
|
|
e.printStackTrace(System.out);
|
|
|
|
throw new TwoException("from inner try");
|
|
|
|
}
|
|
|
|
} catch(TwoException e) {
|
|
|
|
System.out.println(
|
|
|
|
"Caught in outer try, e.printStackTrace()");
|
|
|
|
e.printStackTrace(System.out);
|
|
|
|
}
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
originating the exception in f()
|
|
|
|
Caught in inner try, e.printStackTrace()
|
|
|
|
OneException: thrown from f()
|
2015-12-15 11:47:04 -08:00
|
|
|
at RethrowNew.f(RethrowNew.java:16)
|
|
|
|
at RethrowNew.main(RethrowNew.java:21)
|
2015-06-15 17:47:35 -07:00
|
|
|
Caught in outer try, e.printStackTrace()
|
|
|
|
TwoException: from inner try
|
2015-12-15 11:47:04 -08:00
|
|
|
at RethrowNew.main(RethrowNew.java:26)
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|