Java finally return知识小菜

时间:2022-04-25
本文章向大家介绍Java finally return知识小菜,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

示例代码:

public class FinalTest {
  public static String testTry1() {
    try {
            return "try";

    } catch (Exception e) {
            return "cache";

    } finally {

      System.out.println("finally");
    }
  }
            
  public static String testTry2() {
      try {
            throw new Exception("dd");

    } catch (Exception e) {
           return "cache";

    } finally {

      System.out.println("finally");
    }
  }
           
   public static String testTry3() {
      try { 
            return "try";

    } catch (Exception e) {
            return "cache";

    } finally { 
            return "finally";
    }
  }
            
  public static void main(String[] args) {
    System.out.println("===testTry1===");
    System.out.println(testTry1());
    System.out.println("===testTry2===");
    System.out.println(testTry2());
    System.out.println("===testTry3===");
    System.out.println(testTry3());
  }

}

结果:

===testTry1===

finally

try

===testTry2===

finally

cache

===testTry3===

finally

结论:

1、根据testTry1,testTry2结果可知,当try/catch块中有return声明时,finally块中的代码依旧执行

2、根据testTry3结果可知,try/catch return的值会被finally中return的值覆盖