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;
}