首页 > 代码库 > Java-- 重新抛出异常

Java-- 重新抛出异常

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

catch(Exception e){

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

  throw e;

}

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

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

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

 1 package com.exceptions; 2  3  4 public class Rethrowing { 5      6     public static void f() throws Exception{ 7         System.out.println("originating the exception in f()"); 8         throw new Exception("throw from f()"); 9     }10     11     public static void g() throws Exception{12         try{13             f();14         }catch(Exception e){15             System.out.println("Inside g(), e.printStackTrace()");16             e.printStackTrace(System.out);17             throw e;18         }19     }20     21     public static void h() throws Exception{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 void main(String[] args) {31         // TODO Auto-generated method stub32         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: throw from 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: throw from 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: throw from 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: throw from f()20     at com.exceptions.Rethrowing.h(Rethrowing.java:27)21     at com.exceptions.Rethrowing.main(Rethrowing.java:39)