001package java7; 002 003import com.sandwich.koan.Koan; 004 005import java.io.*; 006 007import static com.sandwich.koan.constant.KoanConstants.__; 008import static com.sandwich.util.Assert.assertEquals; 009 010public class AboutTryWithResources { 011 012 class AutoClosableResource implements AutoCloseable { 013 public void foo() throws WorkException { 014 throw new WorkException("Exception thrown while working"); 015 } 016 017 public void close() throws CloseException { 018 throw new CloseException("Exception thrown while closing"); 019 } 020 } 021 022 class WorkException extends Exception { 023 public WorkException(String message) { 024 super(message); 025 } 026 } 027 028 class CloseException extends Exception { 029 public CloseException(String message) { 030 super(message); 031 } 032 } 033 034 @Koan 035 public void lookMaNoClose() { 036 String str = "first line" 037 + System.lineSeparator() 038 + "second line"; 039 InputStream is = new ByteArrayInputStream(str.getBytes()); 040 String line; 041 /* BufferedReader implementing @see java.lang.AutoCloseable interface */ 042 try (BufferedReader br = 043 new BufferedReader( 044 new InputStreamReader(is))) { 045 line = br.readLine(); 046 //br guaranteed to be closed 047 } catch (IOException e) { 048 line = "error"; 049 } 050 assertEquals(line, __); 051 } 052 053 @Koan 054 public void lookMaNoCloseWithException() throws IOException { 055 String line = "no need to close readers"; 056 try (BufferedReader br = 057 new BufferedReader( 058 new FileReader("I do not exist!"))) { 059 line = br.readLine(); 060 } catch (FileNotFoundException e) { 061 line = "no more leaking!"; 062 } 063 assertEquals(line, __); 064 } 065 066 @Koan 067 public void lookMaNoCloseWithMultipleResources() throws IOException { 068 String str = "first line" 069 + System.lineSeparator() 070 + "second line"; 071 InputStream is = new ByteArrayInputStream(str.getBytes()); 072 String line; 073 //multiple resources in the same try declaration 074 try (BufferedReader br = 075 new BufferedReader( 076 new FileReader("I do not exist!")); 077 BufferedReader brFromString = 078 new BufferedReader( 079 new InputStreamReader(is)) 080 ) { 081 line = br.readLine(); 082 line += brFromString.readLine(); 083 } catch (IOException e) { 084 line = "error"; 085 } 086 assertEquals(line, __); 087 } 088 089 @Koan 090 public void supressException() { 091 String message = ""; 092 try { 093 bar(); 094 } catch (WorkException e) { 095 message += e.getMessage() + " " + e.getSuppressed()[0].getMessage(); 096 } catch (CloseException e) { 097 message += e.getMessage(); 098 } 099 assertEquals(message, __); 100 } 101 102 103 public void bar() throws CloseException, WorkException { 104 try (AutoClosableResource autoClosableResource = 105 new AutoClosableResource()) { 106 autoClosableResource.foo(); 107 } 108 } 109}