๋ฐ์ํ
โถ try-with-resources๋ฌธ
โ
-AutoCloseable ์ธํฐํ์ด์ค
try-with-resources ๋ฌธ๋ฒ์ ์ฌ์ฉํ๋ ค๋ฉด ํด๋น ๋ฆฌ์์ค๊ฐ AutoCloseable ์ธํฐํ์ด์ค๋ฅผ ๊ตฌํํด์ผ ํ๋ค.
AutoCloseable ์ธํฐํ์ด์ค์๋ close( ) ๋ฉ์๋๊ฐ ์๊ณ ์ด๋ฅผ ๊ตฌํํ ํด๋์ค๋ close( )๋ฅผ ๋ช ์์ ์ผ๋ก ํธ์ถํ์ง ์์๋ close( ) ๋ฉ์๋ ๋ถ๋ถ์ด ํธ์ถ๋๋ค.
โ
โ
AutoCloseObj.java
package exception;
public class AutoCloseObj implements AutoCloseable {
@Override
public void close() throws Exception {
System.out.println("๋ฆฌ์์ค๊ฐ close() ๋์์ต๋๋ค.");
}
}
AutoCloseTest.java
package exception;
public class AutoCloseTest {
public static void main(String[] args) {
try (AutoCloseObj obj = new AutoCloseObj()) {
} catch (Exception e) {
System.out.println("์์ธ ๋ถ๋ถ์
๋๋ค.");
}
}
}
AutoCloseObjTest.java
package exception;
public class AutoCloseObjTest {
public static void main(String[] args) {
try (AutoCloseObj obj = new AutoCloseObj()) {
throw new Exception();
} catch (Exception e) {
System.out.println("์์ธ ๋ถ๋ถ์
๋๋ค.");
}
}
}
๋ฐ์ํ
'Java' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Java-๊ธฐ์ด] ์๋ฐ ์ ์ถ๋ ฅ (Stream) (0) | 2021.02.22 |
---|---|
[Java-๊ธฐ์ด] ์์ธ ์ฒ๋ฆฌ ๋ฏธ๋ฃจ๊ธฐ (0) | 2021.02.22 |
[Java-๊ธฐ์ด] ์ปดํ์ผ๋ฌ์ ์ํด ์์ธ๊ฐ ์ฒดํฌ๋๋ ๊ฒฝ์ฐ (0) | 2021.02.22 |
[Java-๊ธฐ์ด] ์์ธ ํด๋์ค (0) | 2021.02.22 |
[Java-๊ธฐ์ด] ์คํธ๋ฆผ (0) | 2021.02.22 |
๋๊ธ