finally
不要在 finally 语句块中使用 return! 当 try 语句和 finally 语句中都有 return 语句时,try 语句块中的 return 语句会被忽略。这是因为 try 语句中的 return 返回值会先被暂存在一个本地变量中,当执行到 finally 语句中的 return 之后,这个本地变量的值就变为了 finally 语句中的 return 返回值。
public class FinallyTest {
public static void main(String[] args) {
System.out.println("返回基本类型的try,返回值为:"+basicMethod());//1
System.out.println("返回基本类型的try finallyReturn(),返回值为:"+basicMethod_finallyReturn());//3
System.out.println("返回对象类型的try,"+objectMethod());//3
System.out.println("返回对象类型的try finallyReturn(),"+objectMethod_finallyReturn());//3
System.out.println("返回对象类型的try catchReturn(),"+objectMethod_catchReturn());//3
}
//返回基本类型的try
public static int basicMethod(){
int a=100;
try {
a = 1;
return a;
}catch (Exception e){
e.printStackTrace();
a = 2;
return a;
}finally {
a = 3;
}
}
//返回基本类型的try
public static int basicMethod_finallyReturn(){
int a=100;
try {
a = 1;
return a;
}catch (Exception e){
e.printStackTrace();
a = 2;
return a;
}finally {
return a = 3;
}
}
//该内部类作为下面objectMethod方法中try返回的类型
public static class MyClass{
public int var;
@Override
public String toString() {
return "返回值为:"+var;
}
}
//返回对象类型的try
public static MyClass objectMethod(){
MyClass myClass = new MyClass();
try {
myClass.var = 1;
return myClass;
}catch (Exception e){
e.printStackTrace();
myClass.var = 2;
return myClass;
}finally {
myClass.var = 3;
}
}
//返回对象类型的try
public static MyClass objectMethod_finallyReturn(){
MyClass myClass = new MyClass();
try {
myClass.var = 1;
return myClass;
}catch (Exception e){
e.printStackTrace();
myClass.var = 2;
return myClass;
}finally {
myClass.var = 3;
return myClass;
}
}
//返回对象类型的try
public static MyClass objectMethod_catchReturn(){
MyClass myClass = new MyClass();
try {
myClass.var = 1;
int i = 1/0;
return myClass;
}catch (Exception e){
e.printStackTrace();
myClass.var = 2;
return myClass;
}finally {
myClass.var = 3;
return myClass;
}
}
}
标签:return,try,finally,myClass,var,MyClass,异常
From: https://www.cnblogs.com/haveanicedayfh/p/17131399.html