Java7 enhanced Try statement to close resources

Source: Internet
Author: User
Tags finally block

Java7 enhanced Try statement to close resources

Traditional way to close resources

?
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.ObjectInputStream;import java.io.ObjectOutputStream; class Student implements Serializable {  private String name;  public Student(String name) {    this.name = name;  }}public class test2 {  public static void main(String[] args) throws Exception {    Student s = new Student("WJY");    Student s2 = null;    ObjectOutputStream oos = null;    ObjectInputStream ois = null;    try {      //创建对象输出流      oos = new ObjectOutputStream(new FileOutputStream("b.bin"));      //创建对象输入流      ois = new ObjectInputStream(new FileInputStream("b.bin"));      //序列化java对象      oos.writeObject(s);      oos.flush();      //反序列化java对象      s2 = (Student) ois.readObject();    } finally { //使用finally块回收资源      if (oos != null) {        try {          oos.close();        } catch (Exception ex) {          ex.printStackTrace();        }      }      if (ois != null) {        try {          ois.close();        } catch (Exception ex) {          ex.printStackTrace();        }      }    }  }}

Use the finally block to close the physical resource and ensure that the close operation is always performed.

Before closing each resource, ensure that reference variables referencing the resource are NOT NULL first.

Use a separate Try...catch block for each physical resource to close the resource, guaranteeing that the exception thrown when the resource is closed does not affect the shutdown of other resources.

The above method causes the finally block code to be very bloated, the program readability is reduced.

Java7 enhanced Try statement to close resources

To address these traditional approaches, JAVA7 has added a try statement that automatically shuts down resources. It allows a pair of parentheses to be followed immediately after the Try keyword, where one or more resources can be declared and initialized, and resources here refer to those resources that must be shown closed at the end of the program (database connections, network connections, etc.), and the try statement will close those resources automatically at the end of the statement.

?
12345678910111213141516171819 public class test2 {  public static void main(String[] args) throws Exception {    Student s = new Student("WJY");    Student s2 = null;    try (//创建对象输出流        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("b.bin"));        //创建对象输入流        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("b.bin"));    )  {      //序列化java对象      oos.writeObject(s);      oos.flush();      //反序列化java对象      s2 = (Student) ois.readObject();    }  }}

A try statement that automatically closes a resource is equivalent to containing an implicit finally block (to close a resource), so the try statement can have neither a catch block nor a finally block.

Attention:

Resources that are automatically closed must implement the closeable or Autocloseable interface. (Closeable is a sub-interface of Autocloseable, and the Close () method declaration in the Closeeable interface throws a IOException; The close () method declaration in the Autocloseable interface throws a exception)

The closed resource must be declared and initialized in parentheses after the try statement. If the program has a try statement that needs to automatically close the resource, it can take multiple catch blocks and a finally block.

Java7 almost all of the "resource Classes" (including various classes of file IO, JDBC Programming connection, statement, etc.). ) is rewritten, and the rewritten resource class implements the Autocloseable or Closeable interface

Java7 enhanced Try statement to close resources

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.