Finally keyword _java in Java

Source: Internet
Author: User
Tags exception handling finally block socket

Final: no polymorphic switch ~

Modifier variable: variable cannot be changed

Cosmetic class: class cannot be inherited

Cosmetic method: Method cannot be overridden

Finally: the last block of statements used in exception handling

Be executed regardless of whether or not the exception is generated ~ ~

Java code

Public final class Finallytest {public 
static void Main (string[] args) { 
try { 
throw new NullPointerException (); 
} catch (NullPointerException e) { 
System.out.println ("The program throws an exception"); 
} finally { 
System.out.println (" A finally statement block ") was executed;}} 

The use of finally keywords in Java

The finally keyword is the best complement to the Java exception handling model, compared to other language models. The finally structure causes the code to execute, regardless of whether or not an exception occurs. Use finally to maintain the internal state of an object and to clean up a non-memory resource. Without finally, your code would be confusing. For example, the following code shows how you must write code to free a non-memory resource without using finally:

Import java.net.*; 
Import java.io.*;

Class withoutfinally 
{public 
void foo () throws IOException 
{ 
//create a socket on either of the free ports 
ServerSocket SS = new ServerSocket (0); 
Try 
{ 
Socket socket = ss.accept (); 
The other code here ... 
} 
catch (IOException e) 
{ 
ss.close ();//1 
throw e; 
} 
//... 
Ss.close (); 2 
} 
}

This code creates a socket and invokes the Accept method. You must close this socket before exiting the method to avoid resource vulnerabilities. To complete this task, we call close at//2, which is the last statement of the method. But what happens if an exception occurs in a try block? In this case, the close call at//2 will never happen. Therefore, you must catch this exception and insert another call to close at//1 before this exception is issued. This will ensure that the socket is closed before exiting the method.

It's cumbersome and error-prone to write code, but it's essential in the absence of finally. Unfortunately, in languages where there is no finally mechanism, programmers may forget to organize their code in this way, resulting in resource vulnerabilities. The finally clause in Java solves the problem. With finally, the preceding code can be rewritten as follows:

Import java.net.*; 
Import java.io.*;
Class withfinally 
{public 
void Foo2 () throws IOException 
{ 
//Create a socket 
serversocket SS = on either of the free ports New ServerSocket (0); 
Try 
{ 
Socket socket = ss.accept (); 
The other code here ... 
} 
Finally 
{ 
ss.close (); 
} 
} 
}

Finally blocks ensure that the Close method is always executed, regardless of whether an exception is emitted within a try block. Therefore, you can ensure that the Close method is always called before exiting the method. This allows you to be sure that the socket is turned off and that you do not have a resource leaking. There is no need to have another catch block in this method. The catch block is provided in the first example just to close the socket, which is now closed through finally. If you do provide a catch block, the code in the finally block executes after the catch block completes.

Finally blocks must be used in conjunction with try or try/catch blocks. In addition, it is not possible to exit a try block without executing its finally block. If a finally block exists, it is always executed. (from that point of view, the statement is correct.) There is a way to exit a try block without executing the finally block. If the code executes a system.exit (0) inside the try; Statement, the application terminates without executing the finally execution. On the other hand, if you dial out the power during the try block execution, finally it is not executed. )

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.