异常书写方式分类
“try-catch-finally"和"try-with-resources”
1."try-catch-finally"方式
public static void writeFile(Path path, String content){
if (Files.notExists(path)) {
throw new RuntimeException("File (" + path + ") doesn't exist!");
}
BufferedWriter writer = null;
try {
writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8);
writer.write(content);
writer.flush();
}catch(Exception e){
e.printStackTrace();
}finally{
if(writer != null){
writer.close();
}
}
}
2."try-with-resources"方式
public static void writeFile(Path path, String content){
if (Files.notExists(path)) {
throw new RuntimeException("File (" + path + ") doesn't exist!");
}
try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
writer.write(content);
writer.flush();
}catch(Exception e){
e.printStackTrace();
}
}
采用try-with-resources,使代码变得非常简洁。try-with-resources的用法就是,在try关键字的后面跟一个括号,把需要关闭的资源定义在括号内。在try块执行完之后会自动的释放掉资源。
什么资源可以被try-with-resources自动关闭?
并不是所有资源都可以被try-with-resources自动关闭的,只有实现了java.lang.AutoCloseable接口的类,才可以被自动关闭。也可以把自己的类编写为可以被try-with-resources自动关闭的类,只需要去实现java.lang.AutoCloseable接口即可。