java异常体系---不要在finally块中使用return、throw

在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块中的非运行时异常。spa

状况二: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 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");
        throw new RuntimeException("finally block 异常了!");
    }    
}
程序运行结果:try block run   》》  finally block run  》》  finally block 异常了!

复制代码

说明:程序告警,finally block does not complete normally。此时编译器不会检查try块、catch块中的非运行时异常。orm

JVM不会再去捕获try块、catch块中的异常,而是获得(使用return时)finally块的返回值或者(使用throw时)finally块中抛出的异常。编译器

结论:

当在finally块中使用return、throw时,编译器不会再对try、catch块中的非运行时异常进行检查,JVM不会再去捕获try块、catch块中的异常,程序的输出以finally块为准,即finally块的返回值或者finally块中抛出的异常。io

当在try块或catch块中遇到return语句时,finally块将在方法返回以前被执行。finally块中的return语句会覆盖try块、catch块中的return语句。合理的作法是在 finally 块以后使用return语句。编译

相关文章
相关标签/搜索