javaSE FileOutputStream, 对IO异常的处理, try...catch


Demo.java:

package cn.xxx.demo;

import java.io.FileOutputStream;
import java.io.IOException;

public class Demo {
	public static void main(String[] args) {
		FileOutputStream fos = null;  // try外面声明流对象。 提升作用域。
		try{
			fos = new FileOutputStream("s:\\a.txt");
			fos.write(100);
		}catch(IOException ex){
			System.out.println(ex);
			throw new RuntimeException("文件写入失败,重试");
		}finally{
			try{
				if(fos!=null)
					fos.close();  // 如果fos为null,会报空指针异常。
			}catch(IOException ex){
				throw new RuntimeException("关闭资源失败");
			}
		}
	}
}


猜你喜欢

转载自blog.csdn.net/houyanhua1/article/details/80702244