首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > J2SE开发 >

1个错误的有关问题

2011-12-31 
1个异常的问题public class Rethrowing {public static void f() throws Exception {System.out.println(

1个异常的问题
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
 我想知道为什么。



[解决办法]
因为Exception是Throwable 一个子类,Throwable 范围比Exception,g()抛出的是大范围的,但你用小范围的Exception 去捕获是不行的。JAVA的原则是大的可以捕获小的,而不能用小的去捕获的大的。

举一反三:
假设g()会抛出一个IOException,在main()中就可以用IOException或者用Exception去捕获,因Exception 比IOException范围大。
[解决办法]
这段没错,只是main中的catch捕捉不到,main就把throwable抛出了

热点排行