Use the Finally keyword to avoid resource vulnerabilities

xiaoxiao2021-03-06  99

Finally keywords are the best supplements to Java exception processing models compared to other languages. The Finally structure has enabled the code to perform, regardless of any abnormal occurrence. Use Finally to maintain the internal state of the object and you can clean up non-memory resources. If you don't have Finally, your code will be very puzzled. For example, the following code description, how do you have to write a code without using Finally, you must release non-memory resources:

Import java.net. *;

Import java.io. *;

Class withoutfinally

{

Public void foo () THROWS IOEXCEPTION

{

/ / Create a socket on any free port

Serversocket SS = New 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. You must close this socket before exiting the method to avoid resource vulnerabilities. To accomplish this task, we call Close at / / 2, which is the last statement of this method. But what if an exception occurs in the TRY block? In this case, the Close call at // 2 will never happen. Therefore, you must capture this exception and insert another call to Close before // before re-issue this exception. This ensures that the socket is turned off before exiting the method.

This writes the code is cumbersome and easy to errors, but this is essential in situations without finaLY. 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 solved this problem. With Finally, the previous code can be rewritten as 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 ServerSocket (0);

Try {

Socket Socket = ss.accept ();

// other code here ...

}

Finally {

ss.close ();

}

}

}

The Finally block ensures that the Close method is always performed, regardless of whether there is an exception in the TRY block. Therefore, it is ensured that the Close method will always be called before exiting the method. This way you can confirm that the socket is turned off and you have no resources. There is no need to have a Catch block in this method. In the first example, the CATCH block is only for closing the socket, now this is closed through Finally. If you really provide a Catch block, the code in the Finally block is executed after the CATCH block is completed.

转载请注明原文地址:https://www.9cbs.com/read-123156.html

New Post(0)