at test.ThrowException.dispose(BException.java:23)
at test.BException.main(BException.java:10)
复制代码
作者: 梁志冰 时间: 2012-9-20 21:42
class BException extends Exception {
public static void main(String[] args) throws Exception {
ThrowException te = new ThrowException();
try {
te.f();//这个方法应该抛出异常BException,但是没有抛出,这是怎么回事
System.out.println("try没有抛异常");
}
catch(Exception e){System.out.println("已经抛出异常");} //这里添加打印语句,发现其实try已经抛出了异常
finally {
te.dispose();//这个方法按预期抛出了AException,
}
}
}
class AException extends Exception {
}
class ThrowException {
void f() throws BException {
throw new BException();//抛出异常
}
void dispose() throws AException {
throw new AException();//抛出异常
}
}
//本来try语句中和finally语句都会抛出一个异常,
// 但是try语句并没有抛出异常,而finally抛出了异常
//try语句先执行,为什么没有抛出异常呢?很奇怪
答:如上面的程序,我们添加两个打印语句,并对try进行捕获,运行结果如下:
已经抛出异常
Exception in thread "main" AException
at ThrowException.dispose(FinalDemo.java:21)
at BException.main(FinalDemo.java:10)
class BException extends Exception {
BException(String x){
System.out.println(x);} //增加构造函数,打印异常
public static void main(String[] args) throws Exception {
ThrowException te = new ThrowException();
try {
te.f();//这个方法应该抛出异常BException,但是没有抛出,这是怎么回事
}
finally {
te.dispose();//这个方法按预期抛出了AException,把这句注释掉的话,前面try语句里面又能抛出异常了
}
}
}
class AException extends Exception {
AException(String x){
System.out.println(x);} //增加构造函数,打印异常
}
class ThrowException {
void f() throws BException {
// throw new BException();//抛出异常
throw new BException("B");//抛出异常
}
void dispose() throws AException {
// throw new AException();//抛出异常
throw new AException("A");//抛出异常
}
}
运行结果1:(保留finally中的异常)
B
A
Exception in thread "main" AException
at ThrowException.dispose(ExceptionDemo.java:25)
at BException.main(ExceptionDemo.java:10)