Java - finally与return

try-return-catch-finally

finally中执行返回值是非常不好的做法. 在一些语言中被直接禁止. 因为有很多副作用.

finally中直接使用return返回值

public static int finallyReturn(){
        try{
            System.out.println("about to return 1");
            return 1;
        } finally {
            System.out.println("about to return 2");
            return 2;
        }
    }

    public static int finallyReturnWithException(){
        int[] ints = new int[0];
        try {
            int n = ints[0];
            return n;
        } finally {
            return 2;
        }
    }

    // 异常完全被finally的return给吞了
    public static int finallyReturnWithException2(){
        try {
            System.out.println("about to throw an exception");
            throw new RuntimeException("doomed");
        } finally {
            return 2;
        }


    }
    
    public static void finallyReturnWithException3(){
        try{
            throw new RuntimeException("something is wrong");
        } finally {
            return;
        }
    }
    
    public static void main(String[] args) {

        int result = finallyReturn();
        System.out.println(result);

        result = finallyReturnWithException();
        System.out.println(result);

        try {
            result = finallyReturnWithException2();
        } catch (Exception e){
            // sadly, this won't happen.
            System.out.println("caught the exception");
        }
        System.out.println(result);
        
        try {
            finallyReturnWithException3();
        } catch (Exception e){
            System.out.println("caught the exception");
        }
        
    }
    

输出:

about to return 1
about to return 2
2
2
about to throw an exception
2

可见finallyreturn的值覆盖了其他流程中的return值. 更可怕的是finally中使用return, 将本来应该抛出的异常也吞了. 所以不应该在finally中使用return.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,803评论 18 399
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,099评论 19 139
  • 一、基本数据类型 注释 单行注释:// 区域注释:/* */ 文档注释:/** */ 数值 对于byte类型而言...
    龙猫小爷阅读 4,295评论 0 16
  • 先上源码: 自己的理解: 1、新建Thread HandlerThread;2、指定ServiceHandler运...
    画十阅读 171评论 0 0
  • 今天轻松跑步,跑了六公里,田园風光也一览无遗,住的地方算是重划区,所以跑步的环境没广东这么大。 回台七天,跑步四次...
    AD_Chen阅读 618评论 0 3