๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Java

[Java-๊ธฐ์ดˆ] try-with-resources๋ฌธ

by ์ฝ”๋”ฉํ•˜๋Š” ๋ถ•์–ด 2021. 2. 22.
๋ฐ˜์‘ํ˜•

โ–ถ 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("์˜ˆ์™ธ ๋ถ€๋ถ„์ž…๋‹ˆ๋‹ค.");
		}
	}
}
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€