item 9 sungjaeyoon - JAVA-JIKIMI/EFFECTIVE-JAVA3 GitHub Wiki
try-finally๋ณด๋ค๋ try-with-resources๋ฅผ ์ฌ์ฉํ๋ผ.
์๋ฐ ๋ผ์ด๋ธ๋ฌ๋ฆฌ์๋ close ๋ฉ์๋๋ฅผ ํธ์ถํด ์ง์ ๋ซ์์ค์ผ ํ๋ ์์์ด ๋ง๋ค.
์๋น์๊ฐ ์์ ๋ง์ผ๋ก finalizer๋ฅผ ์ด์ฉํ์ง๋ง ๋ฏฟ์๋ง ํ์ง ๋ชปํ๋ค.(item8)
์ ํต์ ์ผ๋ก ์์์ ๋ซํ์ ๋ณด์ฅํ๋ ์๋จ์ผ๋ก์ ์๋์ ๊ฐ์ด try-finally๊ฐ ์ฐ์๋ค.
try {
OutputStream out = new FileOutputStream("filePath");
// do something
} finally {
out.close();
}
ํ์ง๋ง 2๊ฐ์ ์์์ ๋ซ์์ผ ํ๋ ๊ตฌ๊ฐ์์๋ ์์ธ๊ฐ ๋ฌด์๋ ์ ์์ผ๋ฉฐ ์ฝ๋์ ๊ฐ๋ ์ฑ๋ ๋จ์ด์ง๋ค.
public void copy(String src, String dst) throws IOException {
InputStream in = new FileInputStream(src);
try {
OutputStream out = new FileOutputStream(dst);
try {
// do something
} finally {
out.close();
}
} finally {
in.close();
}
}
์ด๋ฌํ ๋ฌธ์ ๋ ์๋ฐ 7์์ ๋ฑ์ฅํ try-with-resources๊ตฌ๋ฌธ์ ์ฌ์ฉํ๋ฉด ํด๊ฒฐํ ์ ์๋ค.
๋ฌผ๋ก , AutoCloseable ์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํ ํด๋์ค์ ๋ํด์๋ง ์ฌ์ฉ์ด ๊ฐ๋ฅํ๋ฉฐ ์ฌ๋ฌ ๊ฐ์ ์์๋ ํ ๋ฒ์ ์ฒ๋ฆฌํ ์ ์๋ค.
public void copy() throws IOException {
try (InputStream in = new FileInputStream("filePath");
OutputStream out = new FileOutputStream("filePath")) {
// do something
}
}
์ ๋ฆฌ
๊ผญ ํ์ํด์ผ ํ๋ ์์์ try-with-resources ๋ฌธ์ฅ์ ์ฌ์ฉํ์. ์ฝ๋๋ ๋ ์งง๊ณ ๋ถ๋ช ํด์ง๋ค.