Skip to content

Instantly share code, notes, and snippets.

@sanaulla123
Created May 2, 2012 17:31
Show Gist options
  • Save sanaulla123/2578499 to your computer and use it in GitHub Desktop.
Save sanaulla123/2578499 to your computer and use it in GitHub Desktop.
try-with-resources in Project Coin Java 7
import java.io.Closeable;
import java.io.IOException;
/**
* Created by IntelliJ IDEA.
* User: mohamed
* Date: 2/5/12
* Time: 9:24 PM
* To change this template use File | Settings | File Templates.
*/
public class TryWIthResourcesDemo {
public static void main ( String [] args){
/*
Pre Java 7 Approach
*/
Resource myResource = null;
try{
myResource = new Resource("POOR OLD RESOURCE");
myResource.useResource();
}catch(SomeException ex){
ex.printStackTrace();
}finally {
if (myResource != null) {
try {
myResource.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
Java 7 Approach using the try-with-resource construct
*/
try ( Resource myResource2 = new Resource("TRY-WITH-RESOURCE")){
myResource2.useResource();
}catch ( SomeException | IOException ex){
ex.printStackTrace();
}
}
}
class Resource implements Closeable{
public String resourceName;
public Resource(String resourceName) throws SomeException{
this.resourceName = resourceName;
System.out.println(this.resourceName+" created! Might throw an exception");
}
public void useResource() {
System.out.println("Using the resource "+this.resourceName+"!");
}
@Override
public void close() throws IOException {
System.out.println("Closing the resource "+this.resourceName+"!");
}
}
class SomeException extends Exception{
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment