重新抛出异常——fillInStackTrace()

如果只是把当前的异常对象重新抛出,那么printStackTrace()方法显示的将是原来异常抛出点的调用栈信息,而并非重新抛出点的信息。要想更新这个信息,可以使用fillInStackTrace()方法,这将返回一个Throwable对象,他是通过把当前调用栈信息填入原来的那个异常对象而建立的。如下代码所示:

public class Rethowing {
	public static void f() throws Exception {
		System.out.println("originating the exception in f()");
		throw new Exception("throw from f()");
	}

	public static void g() throws Exception {
		try {
			f();
		} catch (Exception e) {
			System.out.println("Inside g(),e.printStackTrace()");
			e.printStackTrace(System.out);
			throw e;
		}
	}
	
	public static void h() throws Exception {
		try {
			f();
		} catch (Exception e) {
			System.out.println("Inside h(),e.printStackTrace()");
			e.printStackTrace(System.out);
			throw (Exception) e.fillInStackTrace();
		}
	}
	
	public static void main(String[] args) {
		try {
			g();
		} catch (Exception e) {
			System.out.println("main: printStackTrace()");
			e.printStackTrace(System.out);
		}
		System.out.println("--------");
		try {
			h();
		} catch (Exception e) {
			System.out.println("main: printStackTrace()");
			e.printStackTrace(System.out);
		}
	}
}

输入如下:

originating the exception in f()
Inside g(),e.printStackTrace()
java.lang.Exception: throw from f()
	at chapter12.t1.Rethowing.f(Rethowing.java:6)
	at chapter12.t1.Rethowing.g(Rethowing.java:11)
	at chapter12.t1.Rethowing.main(Rethowing.java:31)
main: printStackTrace()
java.lang.Exception: throw from f()
	at chapter12.t1.Rethowing.f(Rethowing.java:6)
	at chapter12.t1.Rethowing.g(Rethowing.java:11)
	at chapter12.t1.Rethowing.main(Rethowing.java:31)
--------
originating the exception in f()
Inside h(),e.printStackTrace()
java.lang.Exception: throw from f()
	at chapter12.t1.Rethowing.f(Rethowing.java:6)
	at chapter12.t1.Rethowing.h(Rethowing.java:21)
	at chapter12.t1.Rethowing.main(Rethowing.java:38)
main: printStackTrace()
java.lang.Exception: throw from f()
	at chapter12.t1.Rethowing.h(Rethowing.java:25)
	at chapter12.t1.Rethowing.main(Rethowing.java:38)

对比main方法中两次方法调用,可以发现调用fillInStackTrace()的那一行成了异常发生的。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值