Traps in java--anomalies (iv)

Source: Internet
Author: User
Tags finally block

First, how to properly close resources using finally

The finally block is always executed regardless of whether the program is abnormal, so it is often used to close the physical resource, ensuring that the resource is always closed.

ImportJava.io.*; Public classCloseresource {//one function reads two files at a time Public voidReadtwofile ()throwsFileNotFoundException, ioexception{bufferedreader br1=NULL; BufferedReader Br2=NULL; FileReader FR=NULL; Try{FR=NewFileReader ("A.txt");//1BR1=NewBufferedReader (FR); intCount = Br1.read ();//2//process Code1 ....FR=NewFileReader ("B.txt");//3Br2=NewBufferedReader (FR); Count= Br2.read ();//4//Process Code2    }finally{         if  (br1! = null   try   // 5 } catch   (Exception e) {e.printstacktrace (); }}  if  (br2! = null  {br2.close ();  // 6 } catch   (Exception e) {e.printstacktrace (); }          }        }}

  this way of shutting down is more secure , using the finally block to close the physical resource, ensuring that the shutdown is always executed, and first ensuring that reference variables referencing the resource are not NULL before closing each resource; Using a separate try...catch for each physical resource Block closes the resource, guaranteeing that the exception thrown when the resource is closed does not affect the shutdown of other resources.

Second, finally and return

Code Listing 1:

 Public classTestdemo {/*** count=5 * int i =++count; add 1 and assign to I--6 * int i =count++; first assign to I plus 1--5 *@return     */     Public Static intTest () {intCount = 5; Try{            //There is a finally block and will not return immediately//finally there is return, and return here does not execute            return++count; } finally{System.out.println ("---finally----" +count); returncount++; }        }     Public Static voidMain (String args[]) {System.out.println (test ()); }}    "Output Result:"---finally----6 6

When a Java program executes a try block, a catch block, and encounters a return statement, the return statement causes the method to end immediately.

The above code, after the system executes the return statement, does not immediately end the method , but rather to find whether the exception process contains a finally block, if there is no finally block, the method terminates, return the corresponding return value. If there is a finally block, the system starts executing the finally block immediately--only after the finally block has finished executing will the system jump back to the end method based on the return statement. If the return statement is used in the finally block to cause the method to end, then the finally block has ended the method, and the system will not jump back to execute any code in the try block, catch block.

Code Listing 2:

classTest { Public intTest () {intx = 1; Try {            return++x; } Catch(Exception e) {}finally {            ++x; }        returnx; }     Public Static voidMain (string[] args) {Test T=NewTest (); inty =t.test ();    System.out.println (y); }}

Output results: 2

If there is a return in the Try statement, then the code behaves as follows:

1. If there is a return value, save the return value to the local variable

2. Execution instruction jumps to the finally statement

3. After executing the FINALLY statement, return the value saved in the local variable table

Note: If you also use a return statement in Finally, such as return ++x. Then Y will be 3. Because the specification specifies that when both try and finally have a return, the return of the try is ignored and the return of finally is used.

Code Listing 3:

 Public Static intTest () {intCount = 5; Try {            Throw NewNullPointerException ("Exception error"); } finally{System.out.println ("Finally"); returncount; }    }     Public Static voidMain (String args[]) {System.out.println (test ()); } Output:finally5

When a program executes a try block and a catch block when it encounters a throw statement, the throw statement causes the method to end immediately, and the system executes the throw statement without immediately throwing an exception to the caller of the method, rather than looking for a finally block in the exception-handling process. If there is no finally block, the program throws an exception immediately, and if there is a finally block, the system immediately begins to execute the finally block--only after the finally block is finished does the system jump back and throw the exception again. If the return statement is used in the finally block to end the method, the system will not jump back to execute a try block, catch block to throw an exception.

Traps in the java--exception (iv)

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.