try-catch-finally小知识:
- try不能单独存在,必须配合catch或者finally
- 可以没有catch,也可以没有finally,但不能都没有
try {
int i = 0;
} catch (Exception e) {
e.printStackTrace();
}finally {
...
}
看起来简单的try-catch-finally,好似没有什么槽点。。。写了一半去笔试了,又遇到这个问题了。
- try-finally , try里有return,finally对值修改,finally无return
int test() {
int i =0;
try {
i++;
System.out.println("try "+i);
try {
throw new Exception("哼哼个哼");
} catch (Exception e) {
e.printStackTrace();
}
return i;
} finally {
i += 10;
System.out.println("finally "+i);
}
}
public static void main(String[] args) {
Ls ls = new Ls();
int test = ls.test();
System.out.println("调用函数返回的结果:"+test);
}
编译后的class字节码文件:
int test() {
int i = 0;
int var2;
try {
++i;
System.out.println("try " + i);
try {
throw new Exception("哼哼个哼");
} catch (Exception var6) {
var6.printStackTrace();
var2 = i;
}
} finally {
i += 10;
System.out.println("finally " + i);
}
return var2;
}
执行结果:
try 1
finally 11
调用函数返回的结果:1
java.lang.Exception: 哼哼个哼
at ls.Ls.test(Ls.java:27)
at ......
看见class字节码文件就知道为什么会是这样的打印结果了。
- 他将try里的return调整到了finally代码块后,函数末尾。
- 异常输出在finally输出后??System.out.print();和System.err.print();是两个不同的输出流,占用2个不同线程,谁先抢到CPU谁就先执行打印【 e.printStackTrace()使用的是System.err输出流】
- 函数调用返回的结果是try后的结果,finally虽然执行了,但没有return finally后的值
try里有return,finally对值修改,finally无return:
先try执行,后finally执行,但返回值为try的结果
- try-catch-finally ; catch和finally中都return,try内无异常
int test() {
int i =0;
try {
i++;
System.out.println("try "+i);
} catch (Exception e)
{
System.out.println("catch");
return 0; // catch-return
}finally {
i += 10;
System.out.println("finally "+i);
return 999; //finally-return
}
}
public static void main(String[] args) {
Ls ls = new Ls();
int test = ls.test();
System.out.println("调用函数返回的结果:"+test);
}
try 1
finally 11
调用函数返回的结果:999
- try-catch-finally ; catch和finally中都return,try内有异常
int test() {
int i =0;
try {
i++;
System.out.println("try "+i);
i = i/0;
} catch (Exception e)
{
System.out.println("catch");
return 0;
}finally {
i += 10;
System.out.println("finally "+i);
return 999;
}
}
public static void main(String[] args) {
Ls ls = new Ls();
int test = ls.test();
System.out.println("调用函数返回的结果:"+test);
}
try 1
catch
finally 11
调用函数返回的结果:999
try-catch-finally 都有return ; 且 try里会出错
try {
i++;
System.out.println("try "+i);
i = i/0;
return -223;
} catch (Exception e)
{
i +=4;
System.out.println("catch "+i);
return -2382738;
}finally {
i += 10;
System.out.println("finally "+i);
return 999;
}
try 1
catch 5
finally 15
调用函数返回的结果:999
从上边可以看出无论try还是catch语句里有return,最终因为finally里的return为准,其他的return在白你以为class字节码时都会被删除。
finally语句里一般不能有return语句,如果有了的话,finally代码块后就不能有其他代码的,会编译不通过。