使用finally回收资源 回收文件资源等等
基本上总会执行,除非之前调用了退出虚拟机的方法
位于catch块之后 return 之后也会执行finaly的语句然后才返回 遇到System,exit 就不会执行finally里的语句了
正常情况下不要在finally中使用return throws等方法导致终止的语句
public class FinallyTest
{
public static void main(String[] args)
{
FileInputStream fis = null;
try
{
fis = new FileInputStream("a.txt");
}
catch (IOException ioe)
{
System.out.println(ioe.getMessage());
//return语句强制方法返回
return ; //①
//使用exit来退出虚拟机
//System.exit(1); //②
}
finally
{
//关闭磁盘文件,回收资源
if (fis != null)
{
try
{
fis.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
System.out.println("执行finally块里的资源回收!");
}
}
}