美文网首页
Java - finally与return

Java - finally与return

作者: xiaofudeng | 来源:发表于2017-11-19 22:31 被阅读0次

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.

相关文章

网友评论

      本文标题:Java - finally与return

      本文链接:https://www.haomeiwen.com/subject/lvxmvxtx.html