流殃的博客

| Comments

return

    public static void main(String[] args) {
        System.out.println(test());
    }
    public static int test()
    {
        int s=0;
        try {
            s++;
            s=s/0;
            return s;
        }
        catch (Exception e)
        {
            s=-1;
            return s;
        }
        finally {
            //return 3;
        }
    }

可以自己写一个代码来进行验证,验证的就是

  1. 如果代码在try之前return,那肯定就直接返回了,和finally没有任何关系
  2. 如果finally中存在return,那实际上返回的就是finally中return的值,因为上面的值都是被finally中的值给覆盖了
  3. 如果finally中的不存在return的值,此时,try中会抛出异常,try和catch中都有return的,那么返回的是catch中的return的值,跟上面一样,也是将上面的覆盖掉了

eixt

    public static int test()
    {
        int s=0;
        try {
            s++;
            s=s/0;
            System.exit(0);
            return s;

        }
        catch (Exception e)
        {
            s=-1;
            System.exit(0);
            return s;
        }
        finally {
            return 3;
        }
    }
//只有0是正常退出,1和-1 都是非正常退出
 System.exit(0)  or EXIT_SUCCESS;  ---> Success
 System.exit(1)  or EXIT_FAILURE;  ---> Exception
 System.exit(-1) or EXIT_ERROR;    ---> Error

在上面代码中进行测试,发现当catch中执行System.exit(0);代码的时候,finally不会执行,但是如果只是在try中有这个代码的时候,finally还是可以执行的

Comments

评论