java catch finally 小知识点

    public static int testA(){
        int a = 0;
        try {
            if(a == 0){
                throw new Exception();
            }
            a = 1;
        }catch (Exception e){
            return a;
        }finally {
            //会被执行,但是 return 结果依然是 0 
            a = 2;
        }
        return a;
    }
	public static void main(String[] args) {
        System.out.println(a);
	}
public class FormTest {

    int a = 0;

    public static FormTest testA(){
        FormTest formTest = new FormTest();
        formTest.a = 0;
        try {
            if(formTest.a == 0){
                throw new Exception();
            }
            formTest.a = 1;
        }catch (Exception e){
            return formTest;
        }finally {
            //会被执行,但是 return 结果 a = 2
            formTest.a = 2;
        }
        return formTest;
    }

	public static void main(String[] args) {
        System.out.println(testA().a);
	}
}

猜你喜欢

转载自my.oschina.net/u/3847203/blog/2962982