14. try catchfinally,try里有return,finally还执行么?
1)、不管是否出现异常,finally块中代码都会执行;
2)、当try和catch中有return时,finally仍然会执行;
3)、finally是在return后面的表达式运算后执行的,具体返回哪一个,看下面的例子,不建议在finally里return,一般finally用于比如关闭资源等;
package com.ws.test;
/**
* @author WeiS
*
*/
public class MyDemo {
public static void main(String[] args) {
System.err.println(exceptionTest());
System.err.println(exceptionTest1());
System.err.println(exceptionTest2());
}
private static int exceptionTest() {
int a = 0;
try {
a = 1;
throw new RuntimeException("this is my exception");
} catch (Exception e) {
return a;
}finally {
a = 3;
return a;
}
}
private static String exceptionTest1() {
try {
throw new RuntimeException("this is my exception");
} catch (Exception e) {
return "abc";
}finally {
return "efd";
}
}
private static String exceptionTest2() {
try {
return "abc";
//throw new RuntimeException("this is my exception");
} catch (Exception e) {
return "abcdef";
}finally {
return "efd";
}
}
}