关于编译时强制检查异常

aipb2008 2008-04-07 09:15:38

public class Prac1{
public static void f() throws TestException{
System.out.println("throw exception from f()");
throw new TestException("!!!warning!!!");
}
public static void main(String[] args){
try{
f();
} catch(TestException te){
System.out.println(te.getMessage());
}
try{
String s = null;
s.length();
} catch(Exception e){
System.out.println(e);
}
finally{
System.out.println("into finally");
}
}
}

TestException是我自己定义的异常类。
我的问题是:
我在f()声明中不加throws TestException,那么编译就会出错,要我添加异常说明。
但是我第2个try-catch中,length方法也没加异常说明吧,我想。

同样,我在调用f()时不使用try-catch,编译就出错,要我添加异常处理。
但是我第2个try-catch中,加不加异常处理都可以。

为什么两者不同???
...全文
83 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
aipb2008 2008-04-07
  • 打赏
  • 举报
回复
才在API文档中找到,非常感谢。
分都给你了。
云上飞翔 2008-04-07
  • 打赏
  • 举报
回复
答:总得好。楼主钻研得很认真,令人敬佩。
关键在于:运行时异常:RuntimeException。
JAVA中规定:只有运行时异常及其子类,才可以不加申明,也可以不要使用try-catch来捕获。
我想:楼主的TestException一定是从Exception继承的,因而不是一个运行时异常,故:1)要在f()后面申明。2)在f()方法中必须要抛出该“非运行时异常”,否则编译程序报错。
 若楼主的TestException是从RuntimeException继承的,则:1)在f()后面申明与不申明该TestException都无所谓。2)在f()方法中抛出与不抛出该TestException也无所谓。 至于: try{
String s = null;
s.length();
} catch(Exception e){
System.out.println(e);
}
中代码,由于Exception是RuntimeException的父亲,而儿子对象可以作为父对象使用,因而不报错。推而广之:只好是运行时异常及其子类,均可以。
如:以下写法都可以
  try{
String s = null;
s.length();
} catch(RuntimeException e){
System.out.println(e);
}

或:
try{
String s = null;
s.length();
} catch(IndexOutOfBoundsException e){
System.out.println(e);
}


一句话:运行时异常可以catch也可以不处理。这就是你说的差别。

62,612

社区成员

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

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