---
title: "JavaIO异常处理"
author: "瓊湳居士"
date: "2015-03-03T11:01:54Z"
tags: []
categories: ["编程语言"]
slug: "javaio"
draft: false
lastmod: "2015-03-03T11:01:54Z"
id: 2188185
url: "https://3138401460.iteye.com/blog/2188185"
---

```java

InputStream input = new FileInputStream(new File("d:" + File.separator + "test.txt"));
		int data = input.read();
		while (data != -1) {
			test(data);// 调用某个方法
			data = input.read();
		}
		input.close();
```

如果此时test()方法出现异常，那么InputStream就不能正确的关闭。因此加入异常处理


```java

try {
			InputStream input = new FileInputStream(new File("d:" + File.separator + "test.txt"));
			int data = input.read();
			while (data != -1) {
				test(data);// 调用某个方法
				data = input.read();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}finally{
			input.close();
		}

```

input.close()放到finally里，无论发生什么异常都会关闭。
此时的input.close()最好先判断
 try{
     if(input != null)
      input.close();
    } catch(IOException e){
    }