注意:以下结果为实际运行结果,结论纯属个人观点,如有错误,请各位大神前辈在评论区留言,看到此文的小伙伴可以去评论区查看留言,避免陷入误区。
1.
private static int add() {
int x = 1;
try {
x++;
System.out.println("try--"+x);
return x;
}catch(Exception e) {
System.out.println("catch--"+x);
return x;
}finally {
x++;
System.out.println("finally--"+x);
}
}
public static void main(String[] args) {
System.out.println("return--"+add());
}
运行结果:
try--2
finally--3
return--2
个人观点:
finally块里的代码不会影响try块里的返回值。
2.
private static int add() {
int x = 1;
try {
x++;
return x++;
}catch(Exception e) {
System.out.println("catch--"+x);
return x;
}finally {
x++;
System.out.println("finally--"+x);
}
}
public static void main(String[] args) {
System.out.println("return--"+add());
}
运行结果:
finally--4
return--2
private static int add() {
int x = 1;
try {
x++;
return ++x;
}catch(Exception e) {
System.out.println("catch--"+x);
return x;
}finally {
x++;
System.out.println("finally--"+x);
}
}
public static void main(String[] args) {
System.out.println("return--"+add());
}
运行结果:
finally--4
return--3
个人观点:
虽然与本次讨论的问题无关,但需要稍微注意一下,x++和++x的区别。
3.
private static int add() {
int x = 1;
try {
x++;
return ++x;
}catch(Exception e) {
System.out.println("catch--"+x);
return x;
}finally {
x++;
System.out.println("finally--"+x);
return x;
}
}
public static void main(String[] args) {
System.out.println("return--"+add());
}
运行结果:
finally--4
return--4
编译器提示:
finally block does not complete normally,在本文最后会解释。
private static int add() {
int x = 1;
try {
x++;
throw new RuntimeException();
}catch(Exception e) {
System.out.println("catch--"+x);
return x;
}finally {
x++;
System.out.println("finally--"+x);
return x;
}
}
public static void main(String[] args) {
System.out.println("return--"+add());
}
运行结果:
catch--2
finally--3
return--3
编译器提示:
finally block does not complete normally,在本文最后会解释。
个人观点:
如果finally块里有return语句,会替代try块或者catch块里的return,成为方法的返回语句。
private static int add() {
int x = 1;
try {
x++;
System.out.println("try--"+x);
}catch(Exception e) {
x++;
System.out.println("catch--"+x);
}finally {
x++;
System.out.println("finally--"+x);
}
return x;
}
public static void main(String[] args) {
System.out.println("return--"+add());
}
运行结果:
try--2
finally--3
return--3
private static int add() {
int x = 1;
try {
x++;
System.out.println("try--"+x);
throw new RuntimeException();
}catch(Exception e) {
x++;
System.out.println("catch--"+x);
}finally {
x++;
System.out.println("finally--"+x);
}
return x;
}
public static void main(String[] args) {
System.out.println("return--"+add());
}
try--2
catch--3
finally--4
return--4
个人观点:
1.try{}catch{}finally{}如果都没有return语句,代码会一直执行到后面的返回语句。
2.代码会顺序执行所有没有异常的语句,知道代码结束或return语句。
在上述过程中,当finally块的包含return语句时,编译器会显示警告,有篇博客对此做了解释,较好,本文不再赘述,放上链接:
finally块的问题(finally block does not complete normally)