java重新抛出异常

重抛异常会把异常重抛给上一级环境中的异常处理程序,同一个try块的后续catch子句将被忽略。
如果只是把当前异常对象重新抛出,那么printStackTrace()方法显示的将是原来抛出点的调用栈信息,而非重新抛出点的信息。要想更新这个信息,可以调用fillStackTrace()方法并返回一个Throwable对象,它是通过把当前调用栈信息填入原来那个异常对象建立的,就像这样:

public class Rethrowing {
    //定义f(),g(),g()中调用f()
    public static void f() throws Exception{
        System.out.println("originating the exception in f()");
        throw new Exception("thrown 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;//重新抛出给main的catch
        }
    }
    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();//调用fillStackTrace()重新抛出新的异常
        }
    }
    public static void main(String[] args){
        try {
            g();
        }catch (Exception e){
            System.out.println("main:printStackTrace()");
            e.printStackTrace(System.out);
        }
        try {
            h();
        }catch (Exception e){
            System.out.println("main:printStackTrace()");
            e.printStackTrace(System.out);
        }
    }
}
/*
output:
originating the exception in f()
Inside g(),e.printStackTrace()
java.lang.Exception: thrown from f()
    at Exception.Rethrowing.f(Rethrowing.java:9)
    at Exception.Rethrowing.g(Rethrowing.java:13)
    at Exception.Rethrowing.main(Rethrowing.java:31)
main:printStackTrace()
java.lang.Exception: thrown from f()
    at Exception.Rethrowing.f(Rethrowing.java:9)
    at Exception.Rethrowing.g(Rethrowing.java:13)
    at Exception.Rethrowing.main(Rethrowing.java:31)
originating the exception in f()
Inside h(),e.printStackTrace()
java.lang.Exception: thrown from f()
    at Exception.Rethrowing.f(Rethrowing.java:9)
    at Exception.Rethrowing.h(Rethrowing.java:22)
    at Exception.Rethrowing.main(Rethrowing.java:37)
main:printStackTrace()
java.lang.Exception: thrown from f()
    at Exception.Rethrowing.h(Rethrowing.java:26)
    at Exception.Rethrowing.main(Rethrowing.java:37)
 */

你可能感兴趣的:(语言)