public class Rethrowing {
  
  public static void f() throws Exception {
    System.out.println("originating the exception in f()");
 throw new    Exception();
  }
  
  public static void g() throws Exception
    try {
      f();
    } catch(Exception e) {
      System.err.println("Inside g(),e.printStackTrace()");
      e.printStackTrace();
      throw e; // 17
    // throw e.fillInStackTrace(); // 18
    }
  }
  public static void
  main(String[] args)  {
    try {
      g();
    } catch(Exception e) {
      System.err.println(
        "Caught in main, e.printStackTrace()");
      e.printStackTrace();
    }
      }
} ///:~
我发现当我把public static void g() throws Exception改成public static void g() throws Throwable
那么下面的MAIN 也要加throws Throwable
 我想知道为什么。

解决方案 »

  1.   

    因为Exception是Throwable 一个子类,Throwable 范围比Exception,g()抛出的是大范围的,但你用小范围的Exception 去捕获是不行的。JAVA的原则是大的可以捕获小的,而不能用小的去捕获的大的。举一反三:
    假设g()会抛出一个IOException,在main()中就可以用IOException或者用Exception去捕获,因Exception 比IOException范围大。
      

  2.   

    当我使用throw e.fillInStackTrace(); 不用throw e;的话
    那异常说明就是throws Throwable 
    如果是因为捕捉的和异常说明的不一致 
    而强行要求MAIN也说明为throws Throwable 。public class ThrowOut {
      public static void
      main(String[] args) throws  Throwable  {
        try {
          throw new Throwable();
        } catch(Exception e) {
          System.err.println("Caught in main()");
        }
      }
    } ///:~那么这段错哪了呢?达人救我。
      

  3.   

    这段没错,只是main中的catch捕捉不到,main就把throwable抛出了