java重新抛出异常_Java-- 重新抛出异常

有时希望把刚捕获的异常重新抛出,尤其是在使用Exception捕获的异常的时候。既然已经得到了对当前异常对象的引用,可以直接把它重新抛出:

catch(Exception e){

Systyem.out.println(“An exception was thrown”);

throw e;

}

重抛异常会把异常抛给上一级环境中的异常处理程序,同一个try块的后续catch子句将被忽略。此外,异常对象的所有信息都得以保持,所以高一级环境中捕获此异常的

处理程序可以从这个异常对象中得到所有信息。

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

1 packagecom.exceptions;2

3

4 public classRethrowing {5

6 public static void f() throwsException{7 System.out.println("originating the exception in f()");8 throw new Exception("throw from f()");9 }10

11 public static void g() throwsException{12 try{13 f();14 }catch(Exception e){15 System.out.println("Inside g(), e.printStackTrace()");16 e.printStackTrace(System.out);17 throwe;18 }19 }20

21 public static void h() throwsException{22 try{23 f();24 }catch(Exception e){25 System.out.println("Inside h(), e.printStackTrace()");26 e.printStackTrace(System.out);27 throw(Exception)e.fillInStackTrace();28 }29 }30 public static voidmain(String[] args) {31 //TODO Auto-generated method stub

32 try{33 g();34 }catch(Exception e){35 System.out.println("main: printStackTrace()");36 e.printStackTrace(System.out);37 }38 try{39 h();40 }catch(Exception e){41 System.out.println("main: printStackTrace()");42 e.printStackTrace(System.out);43 }44 }45

46 }

结果:

1 originating the exception in f()2 Inside g(), e.printStackTrace()3 java.lang.Exception: throwfrom f()4 at com.exceptions.Rethrowing.f(Rethrowing.java:8)5 at com.exceptions.Rethrowing.g(Rethrowing.java:13)6 at com.exceptions.Rethrowing.main(Rethrowing.java:33)7 main: printStackTrace()8 java.lang.Exception: throwfrom f()9 at com.exceptions.Rethrowing.f(Rethrowing.java:8)10 at com.exceptions.Rethrowing.g(Rethrowing.java:13)11 at com.exceptions.Rethrowing.main(Rethrowing.java:33)12 originating the exception in f()13 Inside h(), e.printStackTrace()14 java.lang.Exception: throwfrom f()15 at com.exceptions.Rethrowing.f(Rethrowing.java:8)16 at com.exceptions.Rethrowing.h(Rethrowing.java:23)17 at com.exceptions.Rethrowing.main(Rethrowing.java:39)18 main: printStackTrace()19 java.lang.Exception: throwfrom f()20 at com.exceptions.Rethrowing.h(Rethrowing.java:27)21 at com.exceptions.Rethrowing.main(Rethrowing.java:39)

原文:http://www.cnblogs.com/fxyfirst/p/3805037.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值