Provide some examples when a final...
Provide some examples when a final...
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:
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].
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");
}
}
}
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].
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].
public class Example {
public static void main(String[] args) {
try {
while(true) {
// Infinite loop
}
} finally {
System.out.println("This will not be executed");
}
}
}
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
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào