2014-01-11

Try catch with resources

Introduction

Today I would like to describe a try catch with resource, which is available in Java 7. Additional I show template for Eclipse, which generate such try-resource for reading file.


Try catch in Java 6

In Java 6 (or earlier) you have to write try catch like this:
BufferedReader bin = null;
try{
    bin = new BufferedReader(new FileReader("trolo.txt"));
    String line = null;
    while((line = bin.readLine()) != null){
        // parse line
    }
}catch(IOException e){
    LOG.error("IO exception when creating reader or reading", e);
    throw new MyException(e);
}finally{
    try{
        if(bin != null){
            bin.close();
        }
    }catch(IOException e){
        LOG.error("IO exception when closing", e);
        throw new MyException(e);
    }
}

It is not quite nice... You have to declare BufferedReader before try block and close it in finally (of course if it is not null). Additionally close method could throw IOException which should be handle...

Try catch with resource in Java 7

Java 7 came to us with resources for try. Each resource have to implement interface AutoClosable. It has only one method: close, which is called at the end of try catch with resource. Ant this is an example of use:
try (BufferedReader bin = new BufferedReader(new FileReader("trolo"))){
    String line = null;
    while((line = bin.readLine()) != null){
        // parse line
    }
}catch(IOException e){
    LOG.error("IO exception", e);
    throw new MyException(e);
}
Shorter? Creating, reading or closing BufferedReader could throw exception so we still need catching of IOException, but only once. Finally block is ommited.

Eclipse template

In Eclipse you could define a template, which insert try catch with resource and you job is only name the variables and give file name. I was inspired by this post, to write this template.
${:import(java.io.BufferedReader, java.io.FileReader, java.io.Exception)}
try(BufferedReader ${buffName} = new BufferedReader(new FileReader(${fileName}))){
 String ${line} = null;
 while((${line} = ${buffName}.readLine()) != null) {
        ${cursor}
 }
}catch(IOException e){
    // TODO Auto-generated stub
    throw new UnsupportedOperationException("Not implemented yet");
}

Conclusion

Java 7 came with big improvement for try catch. Now is is shorter to use in try any resource which have to be closed at the end.

No comments:

Post a Comment