Does a finally block always get executed in Java?

前端 未结 30 1413
逝去的感伤
逝去的感伤 2020-11-21 07:24

Considering this code, can I be absolutely sure that the finally block always executes, no matter what something() is?

try         


        
30条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 07:43

    In addition to the other responses, it is important to point out that 'finally' has the right to override any exception/returned value by the try..catch block. For example, the following code returns 12:

    public static int getMonthsInYear() {
        try {
            return 10;
        }
        finally {
            return 12;
        }
    }
    

    Similarly, the following method does not throw an exception:

    public static int getMonthsInYear() {
        try {
            throw new RuntimeException();
        }
        finally {
            return 12;
        }
    }
    

    While the following method does throw it:

    public static int getMonthsInYear() {
        try {
            return 12;          
        }
        finally {
            throw new RuntimeException();
        }
    }
    

提交回复
热议问题