I am expecting the buffered reader and file reader to close and the resources released if the exception is throw.
public static Object[] fromFile(String file
Your usage of try-with-resources will work fine in this particular case, but it is not quite correct in general. You should not chain resources like that because it may lead to unpleasant surprises. Assume you have a variable buffer size:
public static Object[] fromFile(String filePath) throws FileNotFoundException, IOException
{
int sz = /* get buffer size somehow */
try (BufferedReader br = new BufferedReader(new FileReader(filePath), sz))
{
return read(br);
}
}
Assume something went wrong and you ended up with sz
being negative. In this case your file resource (created via new FileReader(filePath)
) will NOT be closed.
To avoid this problem you should specify each resource separately like this:
public static Object[] fromFile(String filePath) throws FileNotFoundException, IOException
{
int sz = /* get buffer size somehow */
try (FileReader file = new FileReader(filePath);
BufferedReader br = new BufferedReader(file, sz))
{
return read(br);
}
}
In this case even if initialization of br
fails file
still gets closed. You can find more details here and here.