IO流之IO的异常处理

如果发生了IO的异常。我们在实际开发中,对异常时如何处理的,我们来演示一下。

public class FileOutputStreamDemo3 {
	public static void main(String[] args) {
		File file = new File("c:\\file.txt");
		//定义FileOutputStream的引用
		FileOutputStream fos = null;
		try {
			//创建FileOutputStream对象
			fos = new FileOutputStream(file);
			//写出数据
			fos.write("abcde".getBytes());
		} catch (IOException e) {
			System.out.println(e.toString() + "----");
throw new RuntimeException("文件写入失败,重试");

		} finally {
			//一定要判断fos是否为null,只有不为null时,才可以关闭资源
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					throw new RuntimeException("关闭资源失败");
				}
			}
		}
	}
}

  

 

posted @ 2018-08-22 11:53  蓝青儿  阅读(309)  评论(0编辑  收藏  举报