Member-only story

Why is it recommended to prioritize using try with resources instead of try finally

1、 Background introduction

Beck Moulton
5 min readOct 15, 2024

try-with-resourcesIt is a new exception handling mechanism introduced in JDK 7, It allows developers to avoid explicit releasetry-catchResources used in statement blocks

For example, we take file resource copying as an example, which is familiar to everyonetry-catch-finallyWrite 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();
}
}
}
}
}

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet