finally return时详解
具体如下代码:
package com.example.demo.java;
import java.util.ArrayList;
import java.util.List;
/**
* Finally 详解
* finally 都是和try catch 配合使用的,代表
* 无论 try catch中的代码是否执行,抛出异常,
* finally中的代码一定执行
*/
public class FinallyTest {
private static int a =10;
private static List<Integer> intList = new ArrayList<Integer>();
public static void main(String[] args) {
System.out.println("finallyTest1:" +finallyTest1());//执行结果返回13
System.out.println("finallyTest2:" +finallyTest2());//执行结果返回12
System.out.println("finallyTest3:" +finallyTest3());//执行结果返回11
System.out.println("finallyTest4:" +finallyTest4().get(0));//执行结果返回20
}
/**
* 即便抛出异常,finally 里的代码依然要执行
* @return
*/
public static int finallyTest1(){
try{
a = 11;
throw new Exception();
}catch (Exception e){
e.printStackTrace();
}finally {
a=13;
return a;
}
}
/**
* 如果finally 中也有return ,会将try catch 中的值覆盖调
* @return
*/
public static int finallyTest2(){
try{
a = 11;
return a;
}catch (Exception e){
e.printStackTrace();
}finally {
return a =12;
}
}
/**
* finally 里没有return,但是改变了返回值,这时不会覆盖
* @return
*/
public static int finallyTest3(){
try{
a = 11;
return a;
}catch (Exception e){
e.printStackTrace();
}finally {
a =14;
}
return a;
}
/**
* finally 里没有return,返回的是引用类型,这时引用类型的值会改变
* @return
*/
public static List<Integer> finallyTest4(){
try{
a = 11;
intList.add(a);
return intList;
}catch (Exception e){
e.printStackTrace();
}finally {
intList.set(0,20);
}
return intList;
}
}
结果如截图: