Member-only story
Why is it recommended to prioritize using try with resources instead of try finally
1、 Background introduction
5 min readOct 15, 2024
try-with-resources
It is a new exception handling mechanism introduced in JDK 7, It allows developers to avoid explicit releasetry-catch
Resources used in statement blocks 。
For example, we take file resource copying as an example, which is familiar to everyonetry-catch-finally
Write it as follows:
public class ResourceTest1 { public static void main(String[] args) {
BufferedInputStream bin = null;
BufferedOutputStream bout = null;
try {
bin = new BufferedInputStream(new FileInputStream(new File( "test.txt")));
bout = new BufferedOutputStream(new FileOutputStream(new File( "out.txt")));
int b;
while ((b = bin.read()) != -1) {
bout.write(b);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//Close file stream
if (bin != null) {
try {
bin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bout != null) {
try {
bout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}