Please go to DobbyKim’s Question of the Day for more questions

A:

Not necessarily.

There are two situations in which a finally block may not execute even if code executes to a try block:

  1. System to terminate
  2. The daemon thread was terminated

Example procedure 1:

package com.github.test;

public class Test {

    public static void main(String[] args) {
        foo();
    }

    public static void foo(a) {
        try {
            System.out.println("In try block...");
            System.exit(0);
        } finally {
            System.out.println("In finally block..."); }}}Copy the code

The results of the program are as follows:

In try block...
Copy the code

The reason is that in the try block, we use the system.exit (0) method, which terminates the currently running virtual machine, which terminates the System. Since the System has been terminated, it is natural that the code in the finally block cannot be executed.

Example program 2:

package com.github.test;

public class Test {

    public static void main(String[] args) {
        Thread thread = new Thread(new Task());
        thread.setDaemon(true);
        thread.start();
        try {
            Thread.sleep(1000);
        } catch(InterruptedException e) { e.printStackTrace(); }}}class Task implements Runnable {

    @Override
    public void run(a) {
        try {
            System.out.println("In try block...");
            Thread.sleep(5000); // Block the thread for 5 seconds
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            System.out.println("In finally block"); }}}Copy the code

The output of the program is:

In try block...
Copy the code

Java threads fall into two broad categories:

  • Daemon threads
  • User Thread

The daemon thread is a thread that provides a general service in the background while the program is running. For example, the garbage collection thread is a daemon thread. Daemons are not an integral part of the program, so when all user threads end, the program terminates, killing all daemons in the process.

In the example above, the program terminates after main is executed, so the daemon thread is killed and the finally block cannot be executed.