异常处理

错误实例

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();

基本正确例子

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

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/