try-catch-finally
- 在try代码块中return的语句先执行,然后执行finally语句,最后返回return的结果
public class FinallyTest1 {
public static void main(String[] args) {
System.out.println(test11());
}
public static String test1() {
try {
System.out.println("try");
return test1();
} finally {
System.out.println("finally");
}
}
public static String test2() {
System.out.println("return statement");
return "after return";
}
}
try
return statement
finally
after return
- finally代码块中的return语句会覆盖try或catch中的return
==> finally中最好不要出现return
public class FinallyTest2 {
public static void main(String[] args) {
System.out.println(test2());
}
public static int test2() {
int b = 20;
try {
System.out.println("try");
return b += 80;
} catch (Exception e) {
System.out.println("catch");
} finally {
System.out.println("finally");
if (b > 25) {
System.out.println("b > 25, b = " + b);
}
return 200;
}
// return b;
}
}
try
finally
b > 25, b = 100
200
在finally中直接返回,finally外的return语句不可达。
注意:
如果finally中没有return语句,则必须在finally下面加任意符合返回值类型的return语句,对return的结果无影响。
- finally中没有return语句的情况下,对变量进行修改:return语句中是基本数据类型,则finally中对变量进行操作不会改变其值;return语句中是引用数据类型,finally中则会更改
public class FinalTest {
public static void main(String[] args) {
System.out.println("------testInt------");
System.out.println(test1());
System.out.println("------testReference------");
// System.out.println(getStudent().getName() + ", " + getStudent().getAge());
System.out.println(getStudent().toString());
}
private static Student getStudent() {
Student alice = new Student("Alice", 20);
try {
System.out.println("try");
return alice.setAge(22);
} catch (Exception e) {
System.out.println("catch");
} finally {
System.out.println("finally");
alice.setAge(23); // 一定会执行
}
return alice.setAge(24); // 该语句不会对 try 或 finally 中的操作产生任何影响;单步调试中 finally 结束直接 return
}
private static int test1() {
int b = 20;
try {
System.out.println("try");
return b += 8;
} catch (Exception e) {
System.out.println("catch");
} finally {
System.out.println("finally");
b = 42;
// return 300;
}
return b;
}
}
class Student {
String name;
int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public Student setAge(int age) {
this.age = age;
return this;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
------testInt------
try
finally
28
------testReference------
try
finally
Student{name=‘Alice’, age=23}
前两部分代码来源于:
Java基础——finally return执行的先后顺序_格局、视野、认知-CSDN博客
在此基础上测试了引用数据类型的情况。