The
try-with-resources statement is introduced in java7, it ensures that each
resource is closed at the end of the statement.
Syntax
try(
resource1;
resource2;
…...
resurce N ) {
}
Prior to Java9, try-with-resources can only manage resources that are declared in the
statement.
public static void writeDataToFile(FileOutputStream fout){ /* in Java 8, try-with-resources can only manage resources that are declared for the statement */ try(FileOutputStream out = fout){ for(int i = 97; i < 110; i++) out.write(i); }catch(Exception e){ System.out.println(e.getMessage()); } }
As
you see above snippet, I defined the variable ‘out’ inside try-with-resource
statement.
From
Java9 on wards, if the resource is referenced by a final or effectively final
variable, a try-with-resources statement can manage the resource without a new
variable being declared.
public static void writeDataToFile(final FileOutputStream fout){ try(fout){ for(int i = 97; i < 110; i++) fout.write(i); }catch(Exception e){ System.out.println(e.getMessage()); } }
Test.java
import java.io.FileOutputStream; public class Test { public static void writeDataToFile(final FileOutputStream fout){ try(fout){ for(int i = 97; i < 110; i++) fout.write(i); }catch(Exception e){ System.out.println(e.getMessage()); } } }
If
you compile the above application in Java9, it runs fine, since the argument to
the method writeDataToFile is declared as final, whereas if you try to compile
the same application in Java8, you will end up in following error.
$javac Test.java
Test.java:6: error: <identifier> expected
try(fout){
^
Test.java:6: error: ')' expected
try(fout){
^
Test.java:6: error: '{' expected
try(fout){
^
Test.java:7: error: ')' expected
for(int i = 97; i < 110; i++)
^
Test.java:7: error: not a statement
for(int i = 97; i < 110; i++)
^
Test.java:7: error: illegal start of type
for(int i = 97; i < 110; i++)
^
Test.java:7: error: not a statement
for(int i = 97; i < 110; i++)
^
Test.java:7: error: ';' expected
for(int i = 97; i < 110; i++)
^
8 errors
No comments:
Post a Comment