Skip to content

@sanaulla123 /gist:2578499
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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
Something went wrong with that request. Please try again.