异常处理

错误实例

  [java]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
InputStream input = new FileInputStream("c:\\data\\input-text.txt"); int data = input.read(); while(data != -1) { //do something with data... doSomethingWithData(data); data = input.read(); } input.close();

基本正确例子

  [java]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
InputStream input = null; try{ input = new FileInputStream("c:\\data\\input-text.txt"); int data = input.read(); while(data != -1) { //do something with data... doSomethingWithData(data); data = input.read(); } } catch(IOException e){ //do something with e... log, perhaps rethrow etc. } finally { if(input != null) { try{ if(input != null) input.close(); } catch(IOException e){ //do something, or ignore. } } }

TRW

  [java]
1
2
3
4
5
6
7
8
9
10
11
try(InputStream input = new FileInputStream("c:\\data\\input-text.txt");){ input = new FileInputStream("c:\\data\\input-text.txt"); int data = input.read(); while(data != -1) { //do something with data... doSomethingWithData(data); data = input.read(); } } catch(IOException e){ //do something with e... log, perhaps rethrow etc. }

参考资料

http://ifeve.com/java-io-exception/