1. finally代码块中有return语句(基本数据类型):
package base;
/**
* Description:
* Author: admin
* Create: 2019-07-19 20:47
*/
public class ExceptionTest {
public static void main(String[] args) {
System.out.println(test());
}
public static int test() {
int i = 0;
try {
i = 1;
return i;
} catch (Exception e) {
i = 2;
return i;
}finally {
i = 3;
return i;
}
}
}
运行结果:3
异常体系中,若 finally 代码块中存在 return 语句,则 try、catch 代码块中的 return 语句失效。
2. finally代码块中无return语句(基本数据类型):
package base;
/**
* Description:
* Author: admin
* Create: 2019-07-19 20:47
*/
public class ExceptionTest {
public static void main(String[] args) {
System.out.println(test1());
}
public static int test1() {
int i = 0;
try {
i = 1;
return i;
} catch (Exception e) {
i = 2;
return i;
}finally {
i = 3;
}
}
}
运行结果:1
若 finally 代码块中无 return 语句,try、catch 有 return 语句时,则 try、catch 代码块会先暂存代码块中的值,然后执行 finally 代码块,最后返回暂存值!!
3. finally代码块中有return语句(引用数据类型):
package base;
/**
* Description:
* Author: admin
* Create: 2019-07-19 20:47
*/
public class ExceptionTest {
private int age;
public static void main(String[] args) {
System.out.println(test2().age);
}
public static ExceptionTest test2() {
ExceptionTest exceptionTest = new ExceptionTest();
try {
exceptionTest.age = 1;
return exceptionTest;
} catch (Exception e) {
exceptionTest.age = 2;
return exceptionTest;
}finally {
exceptionTest.age = 3;
return exceptionTest;
}
}
}
运行结果:3
若 finally 代码块中存在 return 语句,则 try、catch 代码块中的 return 语句失效。
3. finally代码块中无return语句(引用数据类型):
package base;
/**
* Description:
* Author: admin
* Create: 2019-07-19 20:47
*/
public class ExceptionTest {
private int age;
public static void main(String[] args) {
System.out.println(test2().age);
}
public static ExceptionTest test2() {
ExceptionTest exceptionTest = new ExceptionTest();
try {
exceptionTest.age = 1;
return exceptionTest;
} catch (Exception e) {
exceptionTest.age = 2;
return exceptionTest;
}finally {
exceptionTest.age = 3;
}
}
}
运行结果:3
- 此时运行结果就让人有点想不通了?finally 代码块中没有 return 语句,按理说不是应该返回暂存值 1 吗?怎么返回的还是 3 呢?
- finally 是在 return 后面的表达式运算后执行的(此时并没有返回运算后的值,而是先把要返回的值的引用地址保存起来,而不管 finally 中的代码怎么样,最后返回的都是这个引用地址(或者说这个引用地址指向的对象)。
exceptionTest.age = 3
这句使得 exceptionTest 这个对象的地址没变,但是内容变了。
package base;
/**
* Description:
* Author: admin
* Create: 2019-07-19 20:47
*/
public class ExceptionTest {
private int age;
public static void main(String[] args) {
System.out.println(test2().age);
}
public static ExceptionTest test2() {
ExceptionTest exceptionTest = new ExceptionTest();
try {
exceptionTest.age = 1;
return exceptionTest;
} catch (Exception e) {
exceptionTest.age = 2;
return exceptionTest;
}finally {
exceptionTest = new ExceptionTest();//new了个新对象
exceptionTest.age = 3;
}
}
}
运行结果:1
这里很明显又产生了一个新的对象,这个对象和之前的那个 exceptionTest 对象内存地址不一样,exceptionTest.age = 3
是把新对象的内容改为 3 了,而旧对象的 age 属性的值还是 1,所以返回的是 1。