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中,加不加异常处理都可以。为什么两者不同???

解决方案 »

  1.   

    答:总得好。楼主钻研得很认真,令人敬佩。
    关键在于:运行时异常: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也可以不处理。这就是你说的差别。
      

  2.   

    才在API文档中找到,非常感谢。
    分都给你了。