概述:finally组合try...catch语句使用,用于释放资源等收尾工作,无论try...catch语句怎么执行,finally语句肯定会执行
格式:
try{
* 有可能出现问题的代码;
* }catch(异常对象 参数){
* 处理异常;
* }finally{
* 释放资源;
* 清理垃圾;
* }
public class ExceptionDemo1 {
public static void main(String[] args) {
FileWriter fw = null;
try {
fw=new FileWriter("a.txt");
fw.append("hello");
fw.append("world");
System.out.println(2/0);
fw.append("java");
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}catch(ArithmeticException e){
System.out.println("除数不能为0");
}
finally {
try {
if(fw!=null) {
fw.close();
}
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
}
}
网友评论