So I was looking through some of the new features of java 7, including the try-with-resources bit.
I understand how it works and everything, I just noticed that the syntax used to specify the resources is a little odd.
try
(InputStream fis = new FileInputStream(source);
OutputStream fos = new FileOutputStream(target))
{
// stuff
}
}
catch (Exception e) {
// stuff
}
Specifically the definition of resources:
try (InputStream fis = new FileInputStream(source);
OutputStream fos = new FileOutputStream(target))
Is there any other place in java where separating statements within a parenthesis block is valid?
The only other time I can think of is a for loop
for ( ; ; )
but that's not quite the same since there has to be exactly 2 ;
s, and statements are separated with a ,
as in
for (int i = 1, j = 100; i <= 100, j > 0; i = i-1, j = j-1)
So my question is, where did this syntax come from? Is there a reason the statements are ;
delimited instead of ,
delimited? Is there even another comparable language that has a similar use of ;
separated statements inside of a ()
block? I can't think of an example in java, C, or python.
The try-with-resources statement automatically closes all the resources at the end of the statement. A resource is an object to be closed at the end of the program. As seen from the above syntax, we declare the try-with-resources statement by, declaring and instantiating the resource within the try clause.
If an exception is thrown from within a Java try-with-resources block, any resource opened inside the parentheses of the try block will still get closed automatically. The throwing of the exception will force the execution to leave the try block, and this will force the automatic closing of the resource.
For try-with-resources, if an exception is thrown in a try block and in a try-with-resources statement, then the method returns the exception thrown in the try block. The exceptions thrown by try-with-resources are suppressed, i.e. we can say that try-with-resources block throws suppressed exceptions.
We can declare multiple resources in a try block. Try initialization block can have any number of resources resulting in either null or non-null resources.
In general, statements are terminated with semicolons in Java. Note that try-with-resources differs from an assignment like int i = 1, j = 100;
because it doesn't require that each thing being initialized be of the same type. It's really just a series of assignment statements wrapped in parentheses.
That said, I don't think there really needs to be any precedent for using a certain syntax if it's easily understood.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With