1. Introduction
From JDK 9 onwards, you can use the resource reference variables created outside of try block directly in try block resources’ list. That is, the resource reference variables need not be local to try block.
Before Java 9, the resource reference variables created outside of try
block can not be used as a resource in try
. For example, the following code is not possible before Java 9:
BufferedReader br=new BufferedReader(new FileReader("someTextFile.txt")); try(br){ // Some risky code }
Following are two solutions to this problem before Java 9:
1. Creation of resource in try block primary list
You can create the resource in the try block primary list:
try(BufferedReader br=new BufferedReader(new FileReader("someTextFile.txt"))){ //Some risky code }
2. Assign resource with new reference variable
BufferedReader br=new BufferedReader(new FileReader("someTextFile.txt")); try(BufferedReader newBr=br){ //Some risky code }
2. try-with-resources enhancement in Java 9
From JDK 9, you can use the resource reference variables created outside of try block directly in try block resources list.
BufferedReader br=new BufferedReader(new FileReader("someTextFile.txt")); try(br){ // Some risky code }
You just need to make sure that the resource should be either final or effectively final. Effectively final means reassignment to the variable is not possible.
3. Conclusion
In this short article, we discussed the try-with-resources enhancement in Java 9.