try/catch/finally/throw的特性


直接看代码吧,一目了然

import java.lang.Exception;

class Test {
    public int func1()
    {
        int i = 10;
        try
        {
            return i;
        }finally{
            i = 20;
        }
    }

    public int func2()
    {
        int i = 10;
        try
        {
            return i;
        }finally{
            i = 20;
            return 100;
        }
    }

    public StringBuilder func3()
    {
        StringBuilder s = new StringBuilder("ss");
        try
        {
            return s;
        }finally{
            s.append("Add");
        }
    }

    public int func4()
    {
        int x = 0;
        try
        {
            throw new Exception("try Exception");
        } catch (Exception e) {
            throw e;
        }finally{
            return 100;
        }

    }

    // 测试java里的try catch finally的return的特性
    public static void main(String []args) {
        Test t = new Test();

        System.out.println(t.func1()); // 基本类型在try里return值后不受finally的修改所影响
        System.out.println(t.func2()); // finally里的return会覆盖try中的return值
        System.out.println(t.func3()); // 引用类型在try里return返回后会受finally的修改所影响
        System.out.println(t.func4()); // 有finally的存在,try/catch里throw的异常不再向上抛出
    }
}

输出结果:

10
100
ssAdd
100
/latefirstcmt/21