finally块一般用来关闭物理资源(数据库连接,网络连接,磁盘文件等),这些物理资 源必须显式关闭。除非在try块、catch块中调用了退出虚拟机的方法 ( System.exit(0); ),否则不管在try块、catch块中执行怎样的代码,出现怎样的 情况,异常处理的finally块一定会被执行。
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/** * finally关键字 finally块 *
* @author sxj * */
public class FinallyDemo {
public static void main(String[] args) {
FileInputStream in = null;
try {
in = new FileInputStream("E:\\z\\BaseDataType.java");
byte[] buf = new byte[1024];
int count = 0;
//!!此处故意写错,从而触发越界移除,演示finally块的作用!!
while ((count = in.read(buf, 0, buf.length)) > ‐5) {
System.out.println(new String(buf, 0, count));
}
} catch (FileNotFoundException e) {
//文件找不到异常
System.out.println("文件找不到异常");
e.printStackTrace();
} catch (IOException e) {
//IO异常
System.out.println("IO异常");
e.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
System.out.println("finally块中 close()关闭IO流");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}