Project Coin: How to Terminate try-with-resources

In addition to mulling over nulling in the try-with-resources statement, the JSR 334 expert group has decided to slightly amend the syntax of try-with-resources statement: an optional trailing semicolon will now be allowed to terminate the list of resources.

Previously, a semicolon could only be used as a separator between two resources as in

try(Resource r0 = new Resource(); Resource r1 = new Resource(); Resource r2 = new Resource()) {...}

or reformatted as

try(Resource r0 = new Resource();
    Resource r1 = new Resource();
    Resource r2 = new Resource()) {...}

However, including an extraneous semicolon at the end of the list would be rejected as a syntax error:

try(Resource r0 = new Resource();
    Resource r1 = new Resource();
    Resource r2 = new Resource();) {...}  // Illegal under JSR 334 EDR!

While requiring a semicolon at the end of a list of resources would be excessive, especially when there is only a single resource being managed, optionally allowing a terminating resource offers several advantages. First, when adding a resource to the list of resources being managed, there are fewer necessary edits when cutting and pasting. More importantly, programmatic generation of code is simplified since the code generation logic does not need to know ahead of time whether or not a particular resource will be the last one when the declaration for that resource is generated. The simple rule "terminate a resource declaration with a semicolon" will result in acceptable code, even if the code is not ideal style-wise. Finally, allowing an optional trailing semicolon is consistent with the handling of commas in array initializers,

int[] values = {1,
                2,
                3,  // Legal
               };

and the handling of commas in the declaration of enum constants.

enum PrimaryColor {
    RED,
    GREEN,
    BLUE,  // Legal
    ;
}

The full amended grammar for try-with-resources which allows the optional trailing semicolon is:

TryStatement:
try Block Catches
try Block Catchesopt Finally
try ResourceSpecification Block Catchesopt Finallyopt
ResourceSpecification:
( Resources ;opt )
Resources:
Resource
Resource ; Resources
Resource:
VariableModifiersopt Type VariableDeclaratorId = Expression

The necessary compiler changes to implement the revised grammar have been pushed into a JDK 7 integration repository and will appear in a promoted build in due course.

Comments:

Post a Comment:
Comments are closed for this entry.
About

darcy

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today
News

No bookmarks in folder

Blogroll