public
Created

try-with-resources in Project Coin Java 7

  • Download Gist
gistfile1.java
Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
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{
 
 
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.