item 9 huisoo - JAVA-JIKIMI/EFFECTIVE-JAVA3 GitHub Wiki

try-finally(JAVA 6) ๋ณด๋‹ค๋Š” try-with-resources(JAVA 7)๋ฅผ ์‚ฌ์šฉํ•˜๋ผ

  • try-fianally๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ ๋ณด๋‹ค try-with-resources๋ฅผ ์‚ฌ์šฉํ•  ๋•Œ ์ฝ”๋“œ๊ฐ€ ์งง์•„์ง€๊ณ , ์˜ˆ์™ธ ์ฒ˜๋ฆฌ๊ฐ€ ์œ ์šฉํ•˜๋‹ค.
  • try-with-resources๋Š” try๊ฐ€ ์ข…๋ฃŒ๋  ๋•Œ ์ž๋™์œผ๋กœ ์ž์›์„ ํ•ด์ฒดํ•ด์ค€๋‹ค(AutoCloseable ๊ตฌํ˜„ ๋œ ๊ฒฝ์šฐ, close() ๋ฉ”์†Œ๋“œ๋ฅผ ํ˜ธ์ถœํ•œ๋‹ค)
static String firstLineOfFile(String path) throws IOException{
        try(BufferedReader br = new BufferReader(
            new FileReader(path))){
           return br.readLine();
            }
}
  • try(...) ์•ˆ์— Reader ๊ฐ์ฒด๊ฐ€ ํ• ๋‹น ๋˜์–ด์žˆ๋‹ค. ์—ฌ๊ธฐ์— ์„ ์–ธํ•œ ๋ณ€์ˆ˜๋ฅผ try์—์„œ ์‚ฌ์šฉํ•œ๋‹ค.
  • try ๋ฌธ์„ ๋ฒ—์–ด๋‚˜๋ฉด close๋ฅผ ํ˜ธ์ถœํ•œ๋‹ค.
  • ๋ฌธ์ œ์ง„๋‹จ์— ์ข‹๋‹ค. (readLine๊ณผ close ํ˜ธ์ถœ ์–‘์ชฝ์—์„œ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด readLine์—์„œ ๋ฐœ์ƒํ•œ ์˜ˆ์™ธ๊ฐ€ ๊ธฐ๋ก๋œ๋‹ค)
static void copy(String src, String dst) throws IOException{
 InputStream in = new FileInputStream(src);
 try{
    OutputStream out = new FileOutputStream(dst);
    try{
       byte[] buf = new byte[BUFFER_SIZE];
       int n;
       while ((n=in.read(buf)) >= 0)
          out.write(buf,0,n);
    } finally{
        out.close();
    }
 }
}
  • ์ž์›์ด 2์ด์ƒ์ธ ๊ฒฝ์šฐ try-finally ๋ฐฉ์‹์€ ์ง€์ €๋ถ„ํ•˜๋‹ค.
  • try ์˜ˆ์™ธ ๋ฐœ์ƒ ํ›„ finally๋„ ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•  ๊ฒฝ์šฐ finally์•ˆ์˜ ์˜ˆ์™ธ๊ฐ€ ๊ธฐ๋ก์œผ๋กœ ๋‚จ์•„ ๋””๋ฒ„๊ทธ๊ฐ€ ์–ด๋ ต๋‹ค.(๊ฐœ๋ฐœ์ž๋Š” ๋จผ์ € ๋ฐœ์ƒํ•˜๋Š” ์˜ˆ์™ธ๋ฅผ ์•Œ๊ณ  ์‹ถ๋‹ค)
static void copy(String src, String dst) throws IOException{
  try(InputStream in = new FileInputStream(src);
      OutputStream out = new FileOutputStream(dst)){
     byte[] buf = new byte[BUFFER_SIZE];
     int n;
     while((n=in.read(buf))>=0)
          out.write(buf,0,n);
  }
}
  • ๋ฌธ์ œ๋ฅผ ์ง„๋‹จํ•˜๊ธฐ์—๋„ ์ข‹๋‹ค
  • try๋ฌธ๊ณผ close์—์„œ ์˜ˆ์™ธ๊ฐ€ ๋ชจ๋‘ ๋ฐœ์ƒํ•  ๋•Œ, try๋ฌธ ์˜ˆ์™ธ๊ฐ€ ๊ธฐ๋ก๋˜๊ณ  ๋‚˜๋จธ์ง€๋Š” ์ˆจ๊ฒจ์ง„๋‹ค.
  • ์ˆจ๊ฒจ์ง„ ์˜ˆ์™ธ๋“ค์€ ์Šคํƒ ์ถ”์  ๋‚ด์šฉ์— ์ˆจ๊ฒจ์ ธ์žˆ์–ด (suppresed) ๊ผฌ๋ฆฌํ‘œ๋ฅผ ๋‹ฌ๊ณ  ์ถœ๋ ฅ๋œ๋‹ค.
  • ์ž๋ฐ”7์˜ getSuppresed ๋ฉ”์„œ๋“œ๋ฅผ ์ด์šฉํ•˜๋ฉด ํ”„๋กœ๊ทธ๋žจ ์ฝ”๋“œ์—์„œ ๊ฐ€์ ธ์˜ฌ ์ˆ˜ ์žˆ๋‹ค.
static String firstLineOfFile(String path, String defaultVal){
   try(BufferdReader br = new BufferedReader(
          new FileReader(path))){
      return br.readLine();
   }catch(IOException e){
       return defaultVal;
   }
}
  • try-with-resources์—์„œ๋„ catch ์ ˆ ์‚ฌ์šฉ์ด ๊ฐ€๋Šฅํ•˜๋‹ค
  • catch๋ฅผ ์ด์šฉํ•˜์—ฌ ๋‹ค์ˆ˜์˜ ์˜ˆ์™ธ์ฒ˜๋ฆฌ๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค.

์ฐธ๊ณ 

AutoCloseable์ด๋ž€?

  • JAVA7๋ถ€ํ„ฐ ์ถ”๊ฐ€ ๋œ ์ธํ„ฐํŽ˜์ด์Šค.
public interface AutoCloseable{
   void close() throws Exception;
}