在finally块中使用return、throw,会导致编译告警:finally block does not complete normally。
情况一:finally块中没retrun、throw
public static void method_1() { try { System.out.println("try block run"); throw new Exception("try block 异常"); } finally { System.out.println("finally block run"); }}public static void method_2() { try { System.out.println("try block run"); } catch (Exception e) { System.out.println("catch block run"); throw new Exception("catch block 异常了!"); } finally { System.out.println("finally block run"); }}
说明:程序报错,Unhandled exception type Exception。此时编译器会检查try块、catch块中的非运行时异常。
情况二:finally块中有retrun或者throw
public static void method_1() { try { System.out.println("try block run"); throw new Exception("try block 异常"); } finally { System.out.println("finally block run"); return; }}程序运行结果:try block run 》》 finally block runpublic static void method_2(){ try{ System.out.println("try block run"); }catch (Exception e) { System.out.println("catch block run"); throw new Exception("catch block 异常了!"); }finally{ System.out.println("finally block run"); throw new RuntimeException("finally block 异常了!"); } }程序运行结果:try block run 》》 finally block run 》》 finally block 异常了!
说明:程序告警,finally block does not complete normally。此时编译器不会检查try块、catch块中的非运行时异常。
JVM不会再去捕获try块、catch块中的异常,而是得到(使用return时)finally块的返回值或者(使用throw时)finally块中抛出的异常。
结论:
当在finally块中使用return、throw时,编译器不会再对try、catch块中的非运行时异常进行检查,JVM不会再去捕获try块、catch块中的异常,程序的输出以finally块为准,即finally块的返回值或者finally块中抛出的异常。
当在try块或catch块中遇到return语句时,finally块将在方法返回之前被执行。finally块中的return语句会覆盖try块、catch块中的return语句。合理的做法是在 finally 块之后使用return语句。