Câu hỏi phỏng vấn Java
Câu hỏi

Provide some examples when a final...

Câu trả lời

In Java, the finally block is designed to execute after a try block has completed, regardless of whether an exception was thrown or caught. However, there are specific scenarios where the finally block will not be executed:

  1. System.exit() Call: If the System.exit() method is called in the try or catch block, the JVM will terminate immediately, and the finally block will not execute[1][2][4][5][6].

    java Copy
    public class Example {
        public static void main(String[] args) {
            try {
                System.out.println("Inside try block");
                System.exit(0);
            } finally {
                System.out.println("This will not be executed");
            }
        }
    }
  2. JVM Crash: If the Java Virtual Machine (JVM) crashes due to a severe system error like a hardware failure or a critical system resource failure, the finally block will not execute[4].

  3. Infinite Loop or Non-terminating Code: If the try block contains non-terminating code, such as an infinite loop, the finally block will not execute because the control never exits the try block[4].

    java Copy
    public class Example {
        public static void main(String[] args) {
            try {
                while(true) {
                    // Infinite loop
                }
            } finally {
                System.out.println("This will not be executed");
            }
        }
    }
  4. Thread Termination: If the thread running the try block is killed or stopped before it reaches the finally block, the finally block will not execute. This can happen if the thread is forcefully st...

expert

expert

Gợi ý câu hỏi phỏng vấn

middle

What is the main difference between StringBuffer and StringBuilder ?

middle

What is the difference between public , protected , package-private and private in Java?

middle

What is the volatile keyword useful for?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào