Java finally usage, to see which one is enough

This article get permission baeldung team of translation

English original: Www.Baeldung.Com/java-finall...

1 Overview

In this tutorial, we will study the use of finally keyword in Java. We will see how to use it with a try / catch block in error handling. Although the aim is to ensure that the code is finally executed, but we will also discuss special circumstances not execute finally JVM code.

We will also discuss some of the common pitfalls in these traps, finally block may produce unexpected results.

2. What is finally

Finally, the definition of keyword may try finally block. Finally block code is defined, always try and after any catch block, run before the method is completed.

Under normal circumstances, whether or not throw or catch exceptions finally block will be executed.

2.1. A simple example

try {
    System.out.println("The count is " + Integer.parseInt(count));
} catch (NumberFormatException e) {
    System.out.println("No count");
} finally {
    System.out.println("In finally");
}
复制代码

In this example, regardless of the value of the parameter is the number, the JVM is executed finally block and outputs "In finally".

finally 2.2 without the catch block

try {
    System.out.println("Inside try");
} finally {
    System.out.println("Inside finally");
}
复制代码

result

Inside try Insidefinally

2.3 finally usage scenarios

Because regardless of whether an exception will be executed finally happened, so we can perform close the connection in a finally block, close the file operation and release of the thread.

3. finally execution timing

3.1 No abnormal

When the try block of code is completed, the finally block can be performed, even if no abnormality occurs.

try {
    System.out.println("Inside try");
} finally {
    System.out.println("Inside finally");
}
复制代码

Inside try Inside finally

3.2 abnormal but no processor

Even if the exception is not catch, finally block will still be executed.

try {
    System.out.println("Inside try");
    throw new Exception();
} finally {
    System.out.println("Inside finally");
}
复制代码

Even if the exception is not handled appears, JVM will still execute code in the finally block.

Inside try Inside finally Exception in thread "main" java.lang.Exception

3.3 abnormal processor

Exception occurs try block, catch is captured, the finally still be performed.

try {
    System.out.println("Inside try");
    throw new Exception();
} catch (Exception e) {
    System.out.println("Inside catch");
} finally {
    System.out.println("Inside finally");
}
复制代码

Inside try Inside catch Inside finally

3.4 try code block return value

Return even if the try block, can not prevent the execution of the finally block.

try {
    System.out.println("Inside try");
    return "from try";
} finally {
    System.out.println("Inside finally");
}
复制代码

JVM is executed finally block before returning to the calling function.

Inside try Inside finally

3.5 return catch block

In the catch block return statement added, finally the code will still be executed.

try {
    System.out.println("Inside try");
    throw new Exception();
} catch (Exception e) {
    System.out.println("Inside catch");
    return "from catch";
} finally {
    System.out.println("Inside finally");
}
复制代码

result

Inside try Inside catch Inside finally

4 When are finally not be executed

Although usually is finally block to write some code to be executed, but there are some special circumstances would cause the JVM will not execute finally block.

If the operating system interrupt our program, then the finally block may not be executed. There are many other similar behavior led finally block is not executed.

4.1 function calls System.exit

try {
    System.out.println("Inside try");
    System.exit(1);
} finally {
    System.out.println("Inside finally");
}
复制代码

result

Inside try

4.2 calls halt function

try {
    System.out.println("Inside try");
    Runtime.getRuntime().halt(1);
} finally {
    System.out.println("Inside finally");
}
复制代码

Inside try

4.3 daemon thread

If the daemon thread beginning to finally execute the code block, this time there is no other non-daemon threads, then the virtual machine will exit, this time will not wait for JVM finally block daemon thread of execution is completed.

Runnable runnable = () -> {
    try {
        System.out.println("Inside try");
    } finally {
        try {
            Thread.sleep(1000);
            System.out.println("Inside finally");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
};
Thread regular = new Thread(runnable);
Thread daemon = new Thread(runnable);
daemon.setDaemon(true);
regular.start();
Thread.sleep(300);
daemon.start();
复制代码

Export

Inside try Inside try Inside finally

4.4 try code block endless loop

try {
    System.out.println("Inside try");
    while (true) {
    }
} finally {
    System.out.println("Inside finally");
}
复制代码

Try code block an infinite loop, exceptions and does not appear, finally will never be executed.

5. Common pitfalls

We will encounter many pitfalls in the use of finally keyword.

Some bad encoding, such as the presence of the return value or exception thrown finally block.

5.1 ignore abnormal

finally block contains the return statement, no processing uncaught exception.

try {
    System.out.println("Inside try");
    throw new RuntimeException();
} finally {
    System.out.println("Inside finally");
    return "from finally";
}
复制代码

At this time, the try block of code will be ignored RuntimeException, the function returns "from finally" string.

5.2 Other return statement covering

If the finally block the return statement is present, then try and catch block if there is a return statement will be ignored.

try {
    System.out.println("Inside try");
    return "from try";
} finally {
    System.out.println("Inside finally");
    return "from finally";
}
复制代码

This code always returns "from finally".

5.3 throw or return to change behavior

If we finally block throwing an exception, the exception thrown or try and return statement will be ignored in the catch.

try {
    System.out.println("Inside try");
    return "from try";
} finally {
    throw new RuntimeException();
}
复制代码

This code will never have a return value, always throws RuntimeException.

6 Conclusion

In this paper we discuss the use of Java's finally keyword. Then finally we discuss the implementation and without performing the finally block.

Finally, with regard to the development of the common pitfalls of using finally.

This article requires the code, you can go to GitHub supporting the project download.


7. Questions

Translator Added: binding example Part 4, we can think about other ways to make finally get to perform it? Welcome to discuss comments below.


If you think this article helpful to you, welcome thumbs up, forward, comment, Your support is the greatest driving force of my work.

Guess you like

Origin juejin.im/post/5e1346ba5188253a6b371d78