public class Rethrowing
{
public static void f() throws Exception
{
System.out.println("Throwing a Exception from f()");
throw new Exception("from f()");
}
public static void g() throws Throwable
{
try
{
f();
}
catch(Exception e)
{
System.err.println("Inside g(),e.printStackTrace()");
e.printStackTrace(System.err);
//throw e;
throw e.fillInStackTrace();
}
}
public static void main(String [] args) throws Throwable
{
try
{
g();
}
catch(Exception e)
{
System.err.println("Caught in main,e.printStack()");
e.printStackTrace(System.err);
}

}
}
问题是主函数为什么要加上throws Throwable? 如果g()中返回的是Throwable 那么主函数中的catch()将不会捕捉的啊   敬请高手指点~~~

解决方案 »

  1.   

    你不在main中catch这个Throwable,当然需要抛出,让更外层的类来catch了
      

  2.   

    g()抛出的是Throwable,在main方法中只catch的是Exception,所以需要在main方法后添throws Throwable
      

  3.   

    因为Throwable是Exception类的父类,当你用try{}catch(Exception e){}扑捉时,只能扑捉到Exception的子类异常和Exception类型的异常,所以你的main()函数要抛出异常