return finally执行顺序

package com.cfca.testp.program;

public class FinalReturn {
    //finally 和 return的执行顺序; return被分成三步执行,1、计算return的值;2、执行finally块;3、返回return的值
    private int y = 3;
    public static void main(String[] args) {
        FinalReturn fr = new FinalReturn();
        int x = fr.doFinally();
        System.out.println("doFinal, then " + fr.y + "xx=" + x);
    }
    
    public int doFinally() {
        int i = 0;
        try {
            y = 2; //1步
            return this.get(this);
        } catch (Exception ex) {
            i = i + 90;
            return ++this.y + 10;
        } finally {
            System.out.println("finally method going..."); //3步
            this.y = this.y + 100;
        }
    }
    
    public int get(FinalReturn fr) {
        System.out.println("get method is called" + fr.y);
        fr.y++; //2步
        if (fr.y == 3) {
            throw new RuntimeException();
        }
        return fr.y;
    }

}

//下面的方法只抛出FileNotFoundException异常

public static void tryCatch() {
        int i = 10;
        try {            
            try {
                if (i == 10) {
                    System.out.println("inner try happen exception");
                    throw new IOException();
                }
            } finally {
                System.out.println("发生了异常");
                if (i == 10) {
                    throw new FileNotFoundException();
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
 }

猜你喜欢

转载自blog.csdn.net/menghu07/article/details/70211843