Try with resources concise exception trapping mechanism

Source: Internet
Author: User
Tags close close throwable

Through the previous "Java File IO Stream operation Summary", we know how to use the basic input and output streams, but each time we need to close the flow resources at the finally, so that the operation is not verbose and cumbersome, there is no more concise way? This article explains the jdk1.7 introduction of the Try with resources syntax sugar notation.

What is the grammatical sugar1. The reason is called the grammar sugar, gives the person the feeling is very sweet, is very sweet. 2. Under the same function, the syntax sugar will make the code more concise and smooth, the code more semantic natural. 3. Use the compiler to do some processing of these grammars in specific bytecode or specific ways during compilation4. Although syntactic sugars do not provide substantial functional improvements, they can improve performance, or improve the rigor of the grammar, or reduce the chance of coding errors.

Catching exceptions using try with resources

File contents to be read

Sample Code

Package Com.lingyejun.io;import java.io.*;/** * Created by Lingye on 2018/9/28 15:03 */public class Syntacticsugartry {    Call has a finally case value public static final int old_try = 1;    Call the new syntax sugar case value public static final int sugar_try = 2; /** * Perform different methods according to input parameters * * @param type * @return */public InputStream invoketry (int type) {INP        Utstream inputstream = null;                Switch (type) {Case old_try:inputstream = Oldtrycatch ();            Break                Case sugar_try:inputstream = Newtrycatch ();            Break        Default:System.out.println ("error type");    } return InputStream;  }/** * uses the old-fashioned finally notation * * @return */public InputStream Oldtrycatch () {//Build file Object        Inputfile = new File ("D:\\input.txt");        Initializes the input stream inputstream inputstream = null; try {//create byte input stream inputstream = new FilEinputstream (Inputfile);            Read into 1KB byte array byte[] buffer = new BYTE[12];            Reads the data and puts it into the buffer array inputstream.read (buffer);        SYSTEM.OUT.PRINTLN ("Oldtrycatch read output" +new String (buffer));        } catch (Exception e) {e.printstacktrace ();                    } finally {if (InputStream! = null) {try {///Close stream procedure, also possible exception                Inputstream.close ();                } catch (IOException e) {e.printstacktrace ();    }}} return inputstream; }/** * uses syntactic sugar notation * * @return */public InputStream Newtrycatch () {//Build file Object Inpu        Tfile = new File ("D:\\input.txt");        Initializes the input stream inputstream returnstream = null; Try with resource syntax sugar style try (inputstream InputStream = new FileInputStream (inputfile)) {byte[] Buff            ER = new byte[12];     Inputstream.read (buffer);       SYSTEM.OUT.PRINTLN ("Newtrycatch read output" +new String (buffer));        Returnstream = InputStream;        } catch (Exception e) {e.printstacktrace ();    }//omitted the tedious finally return returnstream;        } public static void Main (string[] args) {syntacticsugartry sugartry = new Syntacticsugartry ();        InputStream oldstream = Sugartry.invoketry (old_try);        InputStream Sugarstream = Sugartry.invoketry (sugar_try);        Check if the stream is properly closed try {//try to read again, check if Oldstream.read () is turned off;        } catch (IOException e) {//Closed System.out.println ("Oldstream input stream closed");        try {//retry reading again to check if Sugarstream.read () is turned off;        } catch (IOException e) {//Closed System.out.println ("Sugarstream input stream closed"); }    }}

To view the shutdown of a file pipeline

syntax sugar notation, automatically closes the input stream after execution is complete

View Output Results

It is not difficult to see that the use of syntactic sugar is actually to make our writing code simpler, it seems easier to understand.

Principle of Use

Grammar sugar is a kind of code that almost every language has provided to facilitate the programmer to develop the syntax, it is only a compiler implementation of a few tricks, during compilation in a specific bytecode or specific way to do some of these syntax, developers can directly and conveniently use. Although these syntactic sugars do not provide substantial functional improvements, they can improve performance, improve syntax rigor, or reduce the chance of coding errors.

When you use Jd-gui to open the. Class compilation file for the above classes, the compiler automatically adds a close close action (81 rows and 95 rows) to the resource flow.

/* Error */public InputStream Newtrycatch () {//Byte code://0:new 49java/io/file//3:dup//4: LDC Wuyi//6:invokespecial 53java/io/file:<init> (ljava/lang/string;) V//9:astore_1//10:aconst_nu   ll//11:astore_2//12:aconst_null//13:astore_3//14:aconst_null//15:astore 4// 17:new 55java/io/fileinputstream//20:dup//21:aload_1//22:invokespecial 57java/io/fileinputstream:   <init> (ljava/io/file;) V//25:astore 5//27:bipush//29:newarray <illegal type>// 31:astore 6//33:aload 5//35:aload 6//37:invokevirtual 60java/io/inputstream:read ([B) I//40    : Pop//41:getstatic 29java/lang/system:outljava/io/printstream; 44:new 64java/lang/stringbuilder//47:dup//48:LDC 102//50:invokespecial 68java/lang/stringbui Lder:<init> (ljava/lang/string;) V//53:new 69java/lang/string//56:dup//57:aload 6//59:invokespecial 71java/lang/string:<init> ([B) V//62:invokevi    Rtual 74java/lang/stringbuilder:append (ljava/lang/string;) Ljava/lang/stringbuilder;    65:invokevirtual 78java/lang/stringbuilder:tostring () ljava/lang/string;   68:invokevirtual 37java/io/printstream:println (ljava/lang/string;) V//71:aload 5//73:astore_2//     74:aload 5//76:ifnull +55-131//79:aload 5//81:invokevirtual 87java/io/inputstream:close () V 84:goto +47, 131//87:astore_3//88:aload 5//90:ifnull +8, 98//93:aload    5//95:invokevirtual 87java/io/inputstream:close () V//98:aload_3//99:athrow//100:astore 4 102:aload_3//103:ifnonnull +9//106:aload 4//108:astore_3//109:goto +15-& Gt 124//112:aload_3//113:aload 4//115:if_acmpeq +9, 124//118:aLoad_3//119:aload 4//121:invokevirtual 104java/lang/throwable:addsuppressed (ljava/lang/throwable;) V// 124:aload_3//125:athrow//126:astore_3//127:aload_3//128:invokevirtual 82JAVA/LANG/EXCEP Tion:printstacktrace () V//131:aload_2//132:areturn//Line Number table://Java Source line #75-&G T Byte code offset #0//Java source line #77, byte code offset #10//Java Source line #79-byte code off Set #12//Java source line #80, byte code offset #27//Java source line #81, byte code offset #33/ /Java Source line #82, byte code offset #41//Java source line #83, byte code offset #71//Java SOU Rce line #84, byte code offset #74//Java source line #85, byte code offset #127//Java source line #8 8-> byte code offset #131//Local variable table://startlengthslotnamesignature//01330thisSyntacticSu Gartry//9131inPutFilejava.io.File//111212returnStreamInputStream//1313localobject1object//87163localobject2object 108173localobject3object//12623eException//1514localobject4object//100204localThrowableThrowab Le//25695inputStreamInputStream//31276bufferbyte[]//Exception table://Fromtotargettype//2 77487finally//17100100finally//12126126java/lang/exception}

Reference article:

Https://www.cnblogs.com/jiumao/p/7136369.html

78075206

Try with resources concise exception trapping mechanism

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.