java异常问题总结

[b]Throwable[/b]
Exception
RuntimeException 可以捕获,也可以不捕获(NullPointerException,ArrayIndexOutOfBoundException等)
非运行时异常 必须捕获,否则编译报错
Error
编译器不要求强制处理(如OutOfMemoryError)

throw throws的区别
throw代码中使用,抛出异常
throws声明方法时使用

public class Test {
public Test() {
}

boolean testEx() throws Exception {
boolean ret = true;
try {
ret = testEx1();
} catch (Exception e) {
System.out.println("testEx, catch exception");
ret = false;
throw e;
} finally {
System.out.println("testEx, finally; return value=" + ret);
return ret;
}
}

boolean testEx1() throws Exception {
boolean ret = true;
try {
ret = testEx2();
if (!ret) {
return false;
}
System.out.println("testEx1, at the end of try");
return ret;
} catch (Exception e) {
System.out.println("testEx1, catch exception");
ret = false;
throw e;
} finally {
System.out.println("testEx1, finally; return value=" + ret);
return ret;
}
}

boolean testEx2() throws Exception {
boolean ret = true;
try {
int b = 12;
int c;
for (int i = 2; i >= -2; i--) {
c = b / i;
System.out.println("i=" + i);
}
return true;
} catch (Exception e) {
System.out.println("testEx2, catch exception");
ret = false;
throw e;
} finally {
System.out.println("testEx2, finally; return value=" + ret);
return ret;
}
}

public static void main(String[] args) {

String s = new String(new char[1 << 30]);

Test test = new Test();
try {
test.testEx();
} catch (Exception e) {
e.printStackTrace();
}
}
}


[color=red]如果你的答案是这个,那就错了[/color]
i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, catch exception
testEx1, finally; return value=false
testEx, catch exception
testEx, finally; return value=false

[size=medium]上面的测试代码有 [color=darkred]两个坑[/color]
1,i/0 会抛出一个运行时异常即RunntimeException,可以捕获也可以不捕获
2,testEx2 [color=darkred]catch 中的 throw 相当于一个结束语句,在执行完finally语句块之后才会被执行[/color],
[color=darkred]but...finally中 已经 return结束[/color] (或者 再次throw),catch 中的 throw不会执行 也就不会抛出异常,testEx1中也不会接收异常[/size]

正确的打印结果
i=2
i=1
testEx2, catch exception
testEx2, finally; return value=false
testEx1, finally; return value=false
testEx, finally; return value=false

最后附一张高清图片

[img]http://dl2.iteye.com/upload/attachment/0104/7858/95140507-89e8-396e-ba68-b1718cdc7381.jpg[/img]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值