大家都知道在try…catch…finally语句块中,finally是肯定必然执行的;catch语句块是在出现异常时才会执行的;
猜测一下,下面的代码返回值是多少?是10? 11? 12? 13?
public static int print() {
int a = 10;
try {
a = 11;
return a;
}catch (Exception e) {
a = 12;
}finally {
a = 13;
}
}
返回值为11;这是大家都知道的;但是通过调试代码可知,a的最终值为13
调试:
public static int print() {
int a = 10;
try {
a = 11;
return a;
}catch (Exception e) {
a = 12;
return a;
}finally {
a = 13;
}
}
返回值为11;通过调试,a的最终值为13
public static int print() {
int a=10;
try{
a=11;
return a;
}catch(Exception e){
a = 12;
}finally {
a=13;
return a;
}
}
返回值为13;通过调试,a的最终值为13
public static int print2() {
int a = 10;
try {
a = 11;
}catch (Exception e) {
a = 12;
return a;
}finally {
a = 13;
return a;
}
}
返回值为13;通过调试,a的最终值为13
public static int print2() {
int a = 10;
try {
a = 11;
return a;
}catch (Exception e) {
a = 12;
return a;
}finally {
a = 13;
return a;
}
}
返回值为13;通过调试,a的最终值为13
有没有发现,在finally语句块中如果有return语句,则就会返回finally语句块中的内容;
如果finally语句块中没有return语句,则就会返回try语句块中的内容,即使catch语句块中有返回值也起不到作用,因为catch语句块只有在出现异常时才会执行;
其实:
(1)异常体系中,若finally代码块中存在return语句,则try、catch语句失效。
(2)若finally无return,try有return语句,则try代码块先暂存代码块中的值,然后在代码块中还是该进行怎样的操作就进行怎样的操作,变量的值该怎么变化就怎么变化,最后执行finally代码块,只不过最终返回的是try语句块中的暂存值。
对于基本类型是这样,对于对象也是这样:
class Person{
public int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class Test {
public static Person test() {
Person person = new Person();
try {
person.age = 1;
return person;
}catch (Exception e) {
person.age = 2;
return person;
}finally {
person = new Person();
person.age = 3;
return person;//finally语句块中有return语句
}
}
public static void main(String[] args) {
System.out.println(test().age);
}
}
运行结果为:
而:
class Person{
public int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class Test {
public static Person test() {
Person person = new Person();
try {
person.age = 1;
return person;
}catch (Exception e) {
person.age = 2;
return person;
}finally {
person = new Person();
person.age = 3;
//finally语句块中无return语句
}
}
public static void main(String[] args) {
System.out.println(test().age);
}
}
返回值为: