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中,加不加异常处理都可以。为什么两者不同???
解决方案 »
- 关于clone(),protected访问符的问题求解
- java se5中enum的使用问题
- javad的C/S程序怎样得到网络WEB服务器上的某个目录中的文件
- 关于java调用dll的Native Library Problems
- interface Interaction {}和getFilePointer() 是做什么用的?
- 一个小程序,请帮忙啊
- 谁能告诉我一般的java程序员一月至多少钱?java高手呢?
- 关于java中的按值传递和按址传递
- 高分求教,在线等待,问题复杂!!!!!!
- 如何编程给windows 2000& xp 添加用户。
- 请问哪个类可以在一个指定的区域里面显示图像,用什么方法
- 求救各位高手
关键在于:运行时异常: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也可以不处理。这就是你说的差别。
分都给你了。