The finally key in Java is generally used with try. After the program enters the try block, no matter whether the program aborts due to an exception or returns to terminate in other ways, the content of the finally block will definitely be executed. Write an example to illustrate:
public class TryAndFinallyTest { public static void main(String[] args) throws Exception{ try{ int a = testFinally(2); System.out.println("Result returned by exception a:"+a); }catch(Exception e ){ int b = testFinally(1); System.out.println("Result returned by normal:"+b); } int b = testFinally(3); System.out.println("Result returned by break:" +b); b = testFinally(4); System.out.println("return returns result:"+b); } static int testFinally(int i) throws Exception{ int flag = i; try{//Once you go in : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : : try scope Whether the program throws an exception or other interruption, the content of finally will be executed switch(i){ case 1:++i;break;//The program ends normally case 2:throw new Exception("Exception under test "); case 3:break; default :return -1; } } finally{ System.out.println("finally coming when i="+flag); } return i; } }
The execution results are as follows
Finally coming when i=2finally coming when i=1 The result returned normally b:2finally coming when i=3break returns result:3finally coming when i=4return returns result:-1
The result shows that no matter what the above situation is, the finally block will always be executed.
Compared to other language models, the finally keyword is the best addition to the Java exception handling model. The finally structure allows the code to always execute regardless of whether the exception occurs. Use finally to maintain the internal state of an object and to clean up non-memory resources. Without finally your code will be confusing. For example, the following code illustrates how you have to write code to free non-memory resources without using finally:
import java.net.*; import java.io.*; class WithoutFinally { public void foo() throws IOException { //Create a socket on any free port ServerSocket ss = ne w ServerSocket(0); try { Socket socket = ss.accept(); //Other code here... } catch (IOException e) { ss.close(); //1 throw e; } //... ss.close(); / /2 } }
This code creates a socket and calls the accept method. Before exiting the method, you must close this socket to avoid resource vulnerabilities. To accomplish this task, we call close at //2, which is the last statement of the method. But what happens if an exception occurs in the try block? In this case, the close call at //2 never happens. Therefore, you have to catch this exception and insert another call to close at //1 before reissueing this exception. This ensures that the socket is closed before exiting the method.
Writing code like this is both cumbersome and error-prone, but it is essential without finally. Unfortunately, in languages without a finally mechanism, programmers may forget to organize their code in this way, resulting in resource vulnerabilities. The finally clause in Java solves this problem. With finally, the previous code can be rewritten into the following form:
import java.net.*; import java.io.*; class WithFinally { public void foo2() throws IOException { //Create a socket on any free port ServerSocket ss = new S serverSocket(0); try { Socket socket = ss.accept(); //Other code here... } finally { ss.close(); } } }
The finally block ensures that the close method is always executed regardless of whether an exception is issued within the try block. Therefore, it is ensured that the close method is always called before exiting the method. This way you can be sure that the socket is closed and that you have not leaked resources. There is no need for another catch block in this method. The catch block is provided in the first example just to close the socket, now this is closed by finally. If you do provide a catch block, the code in the finally block is executed after the catch block is finished.
The finally block must be used with the try or try/catch block. Furthermore, it is not possible to exit the try block without executing its finally block. If the finally block exists, it will always execute. (This statement is correct from that point of view. There is a way to exit the try block without executing the finally block. If the code executes a System.exit(0); statement inside the try, the application terminates without Execute finally execution. On the other hand, if you turn off power during the try block execution, finally won't do it either.)