1个异常的问题

hunter1206 2008-03-12 01:24:00
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
我想知道为什么。

...全文
104 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
TYLEO 2008-03-12
  • 打赏
  • 举报
回复
这段没错,只是main中的catch捕捉不到,main就把throwable抛出了
hunter1206 2008-03-12
  • 打赏
  • 举报
回复
当我使用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()");
}
}
} ///:~

那么这段错哪了呢?

达人救我。
awusoft 2008-03-12
  • 打赏
  • 举报
回复
因为Exception是Throwable 一个子类,Throwable 范围比Exception,g()抛出的是大范围的,但你用小范围的Exception 去捕获是不行的。JAVA的原则是大的可以捕获小的,而不能用小的去捕获的大的。

举一反三:
假设g()会抛出一个IOException,在main()中就可以用IOException或者用Exception去捕获,因Exception 比IOException范围大。

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧