Download TryWithResources.java
1: // Demo of Java 7 try-with-resources. 2: // Written 1/2012 by Wayne Pollock 3: // Adapted from an article on TheServerSide.com 12/29/2011, 4: // "Use try-with-resources: Language Enhancements for the Java 7 OCPJP Exam" 5: // by Sal Pece and Cameron McKenzie 6: 7: public class TryWithResources 8: { 9: public static void main ( String [] args ) 10: { 11: try ( OpenTheWindow win = new OpenTheWindow() ) 12: { 13: System.out.println( "Window is open." ); 14: } 15: catch ( Exception e ) { 16: System.out.println( "Exception caught" ); 17: } 18: finally { 19: System.out.println( "In finally clause." ); 20: } 21: } 22: } 23: 24: class OpenTheWindow implements AutoCloseable 25: { 26: public OpenTheWindow () 27: { 28: System.out.println( "The window is opening." ); 29: } 30: 31: public void close () throws Exception 32: { 33: System.out.println( "The window is closed." ); 34: } 35: } 36: 37: 38: /****************************************** 39: Output: 40: 41: C:\Temp>java TryWithResources 42: The window is opening. 43: Window is open. 44: The window is closed. 45: In finally clause. 46: 47: ******************************************/