Explains the basic use of finally statements in Java programming

  • 2020-04-01 04:24:32
  • OfStack

In Java, the finally key is generally used with the try. After the program enters the try block, the contents of the finally block must be executed, whether the program is aborted due to an exception or otherwise returned to terminate.    


public class TryAndFinallyTest { 
 
  public static void main(String[] args) throws Exception{ 
    try{ 
    int a = testFinally(2); 
    System.out.println(" The result returned by the exception a:"+a); 
    }catch(Exception e){ 
      int b = testFinally(1); 
      System.out.println(" Normal return results b:"+b); 
    } 
    int b = testFinally(3); 
    System.out.println("break Return result :"+b); 
     
     b = testFinally(4); 
    System.out.println("return Return result :"+b); 
     
  } 
   
  static int testFinally(int i) throws Exception{ 
    int flag = i; 
    try{//Once inside the try range, the contents of finally are executed regardless of whether the program throws an exception or other interrupt situations
      switch(i){ 
        case 1:++i;break;//Normal end of program
        case 2:throw new Exception(" Test for exceptions "); 
        case 3:break; 
        default :return -1; 
      } 
    }finally{ 
      System.out.println("finally coming when i="+flag); 
    } 
    return i; 
  } 
} 

The results are as follows


finally coming when i=2

finally coming when i=1

 Normal return results b:2

finally coming when i=3

break Return result :3

finally coming when i=4

return Return result :-1

The result is that in either case, the finally block will always be executed.            

Compared to models in other languages, the finally keyword is the best complement to the Java exception handling model. A finally structure enables the code to always execute regardless of whether an exception occurs. Finally is used to maintain the internal state of an object and to clean up non-memory resources. Without finally, your code would be convoluted. For example, the following code illustrates how you must write code to free non-memory resources without finally:


import java.net.*; 
import java.io.*; 
 
   class WithoutFinally 
{ 
   public void foo() throws IOException 
{ 
//Create a socket on any idle port
ServerSocket ss = new ServerSocket(0); 
try 
    { 
    Socket socket = ss.accept(); 
    //The rest of the 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 the socket to avoid resource vulnerabilities. To do this, 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 will never happen. Therefore, you must catch the exception and insert another call to close at //1 before issuing the exception again. This ensures that the socket is closed before exiting the method.

Writing code this way is cumbersome and error-prone, but it is essential in the absence of finally. Unfortunately, ina language without a finally mechanism, programmers can forget to organize their code in this way, leading to resource holes. The finally clause in Java solves this problem. With finally, the previous code can be rewritten as follows:


import java.net.*; 
import java.io.*; 
 
class WithFinally 
{ 
public void foo2() throws IOException 
{ 
//Create a socket on any idle port
ServerSocket ss = new ServerSocket(0); 
try 
    { 
   Socket socket = ss.accept(); 
   //The rest of the 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, you can be sure that the close method will always be called before exiting the method. This way you can be sure that the socket is closed and that you are not leaking resources. There is no need for another catch block in this method. The catch block was provided in the first example just to close the socket, which is now closed by finally. If you do provide a catch block, the code in the finally block executes after the catch block completes.

The finally block must be used in conjunction with a try or try/catch block. In addition, it is impossible to exit a try block without executing its finally block. If a finally block exists, it will always execute. From that point of view, the statement is correct. There is a way to exit the try block without executing the finally block. If the code executes a System. Exit (0) inside the try; Statement, the application terminates without executing finally. On the other hand, if you unplug the power during the execution of the try block, then the finally won't execute either.


Related articles: