当前位置:网站首页>try-catch-finally

try-catch-finally

2022-06-25 11:20:00 User 9854323

public class Main {

    public static void main(String[] args) {
        System.out.println(" return :"WithException());
    }

    public static int WithException() {
        int i = 10;
        try {
            System.out.println("i in try block is : " + i);
            i = i / 0;
            return --i;
        } catch (Exception e) {
            System.out.println("i in catch - form try block is : " + i);
            --i;
            System.out.println("i in catch block is : " + i);
            return --i;
        } finally {
            System.out.println("i in finally - from try or catch block is--" + i);
            --i;
            System.out.println("i in finally block is--" + i);
             return --i;
        }
    }
}

Output :

i in try block is : 10
i in catch - form try block is : 10
i in catch block is : 9
i in finally - from try or catch block is--8
i in finally block is--7
 return :6

If changed to the following ( final return sentence ):

public class Main {

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

    public static int WithException() {
        int i = 10;
        try {
            System.out.println("i in try block is : " + i);
            i = i / 0;
            return --i;
        } catch (Exception e) {
            System.out.println("i in catch - form try block is : " + i);
            --i;
            System.out.println("i in catch block is : " + i);
            return --i;
        } finally {
            System.out.println("i in finally - from try or catch block is--" + i);
            --i;
            System.out.println("i in finally block is--" + i);
            // return --i;
        }
    }
}

Output :

i in try block is : 10
i in catch - form try block is : 10
i in catch block is : 9
i in finally - from try or catch block is--8
i in finally block is--7
 return :8

summary : 1、finally There is no return when , After execution try or catch Of the statement return After that, it will be executed finally.( and return The value of will be temporarily stored in the stack , wait for finally After execution, return to ) 2、finally There are return when , Will still carry out try or catch Of the statement return, But the end result is finally Statement return.

原网站

版权声明
本文为[User 9854323]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206251056180406.html