java学习笔记,异常机制
异常机制结构图:
Throwable也是继承object类的。
异常和错误:异常是在代码中解决的,错误简单点说就是电脑疯了。
在上图中IOException属于可查异常,在写代码是必须捕获或者是抛出,不然不能通过编译。RuntimeException和error属于不可查异常,只有在运行时才能发现错误。
笔记:
如果抛出的异常在方法内就被捕获到了,那么这个方法就算声明了异常抛出也不会抛出异常。
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捕获了,不会再抛出了,所以不会执行testEx1中的catch*/
} catch(Exception e){
System.out.println("testEx2, catch exception");
ret=false;
//throw e;//如果加入了这句话,不管有没有声明抛出异常,都会抛出异常。但是return会不可达。
return false;
}finally {
System.out.println("testEx2, finally; return value=" + ret);
//return ret;
}
}
public static void main(String[] args) {
Test testException1 = new Test();
try {
testException1.testEx();
} catch (Exception e) {
e.printStackTrace();
}
}
}
输出结果:
但是可以强行抛出:解释看注释,运行结果:
finally与return的执行顺序
1、finally代码块的语句在return之前一定会得到执行
2、如果try块中有return语句,finally代码块没有return语句,那么try块中的return语句在返回之前会先将要返回的值保存,之后执行finally代码块,最后将保存的返回值返回,finally代码块虽然对返回值进行修改也不影响返回值,因为要返回的值在执行finally代码块之前已经保存了,最终返回的是保存的旧值(值传递)。
3、如果try块和finally块都有返回语句,那么虽然try块中返回值在执行finally代码块之前被保存了,但是最终执行的是finally代码块的return语句,try块中的return语句不再执行。
4、catch块和try块类似,会在执行finally代码块执行前保存返回值的结果,finally语句中有return语句则执行finally的return语句,没有则执行catch块中的return语句,返回之前的保存值。
5、如果try和catch中没有return。则finally代码块中的更改有效。