Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Khối finally có thực thi sau return trong phương thức Java không?

Có, khối finally sẽ được thực thi ngay cả sau câu lệnh return trong phương thức.

Khối finally luôn thực thi dù có exception hay không. Chỉ khi gọi tường minh System.exit() trong finally block thì nó mới không chạy. Có vài trường hợp finally không chạy: JVM crash, mất điện, crash phần mềm. Ngoài ra, finally block luôn thực thi.

Ví dụ

public class FinallyBlockAfterReturnTest { 
    public static void main(String[] args) { 
        System.out.println(count()); 
    } 
    public static int count() { 
        try { 
            return 1; 
        } catch(Exception e) { 
            return 2; 
        } finally { 
            System.out.println("Finally block will execute even after a return statement in a method"); 
        } 
    } 
}

Kết quả

Finally block will always excute even after a return statement in a method 1