Source of TryWithResources.java


  1: public class TryWithResources {
  2: 
  3:         public static void main(String[] args) throws Exception {
  4: 
  5:                 try ( OpenDoor door = new OpenDoor() ) {
  6:                         door.swing(); /*this throws a SwingExecption*/
  7:                 }
  8:                 catch (Exception e) { 
  9:                         System.out.println("Is there a draft? " + e.getClass());
 10:                 }
 11:                 finally {
 12:                         System.out.println("I'm putting a sweater on, regardless. ");
 13:                 }
 14:         }
 15: }
 16: 
 17: class OpenException extends Exception {}
 18: class SwingException extends Exception {}
 19: class CloseException extends Exception {}
 20: 
 21: /*
 22: class OpenDoor implements AutoCloseable {
 23: 
 24:         public OpenDoor() throws Exception {
 25:                 System.out.println("The door is open.");
 26:         }
 27:         public void swing() throws Exception {
 28:                 System.out.println("The door is becoming unhinged.");
 29:                 throw new SwingException();
 30:         }
 31: 
 32:         public void close() throws Exception {
 33:                 System.out.println("The door is closed.");
 34:     }
 35: }
 36: */
 37: 
 38: class OpenDoor implements AutoCloseable {
 39: 
 40:         public OpenDoor() throws Exception {
 41:                 System.out.println("The door is open.");
 42:         }
 43:         public void swing() throws Exception {
 44:                 System.out.println("The door is becoming unhinged.");
 45:                 throw new SwingException();
 46:         }
 47: 
 48:         public void close() throws Exception {
 49:                 System.out.println("The door is closed.");
 50:                 throw new CloseException(); // throwing CloseException 
 51:         }
 52: }
 53: 
 54: /*
 55:  * From: 
 56:  * https://www.theserverside.com/tutorial/OCPJP-OCAJP-Java-7-Suppressed-Exceptions-Try-With-Resources
 57: /*
 58:  * */