Post

try-catch์™€ try-with-resources

try-catch-finally

try-catch-finally ๋ฌธ์€ ์ž๋ฐ”7 ์ด์ „์— ๋‚˜์˜จ ์˜ˆ์™ธ ์ฒ˜๋ฆฌ ๊ตฌ๋ฌธ์œผ๋กœ ๋ชจ๋“  ๊ฐ์ฒด๋ฅผ ํฌํ•จํ•  ์ˆ˜ ์žˆ๋‹ค.

์‚ฌํšฝ ํ›„ ๋ฐ˜๋‚ฉ์„ ํ•ด์ฃผ์–ด์•ผ ํ•˜๋Š” ์ž์›๋“ค์€ Closeable ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ตฌํ˜„ํ•˜๊ณ  ์žˆ์œผ๋ฉฐ ์‚ฌ์šฉ ํ›„ close ๋ฉ”์„œ๋“œ๋ฅผ ์ง์ ‘ ํ˜ธ์ถœํ•˜์—ฌ ๋ฐ˜๋‚ฉํ•ด์•ผ ํ•œ๋‹ค.

์ž์› ๋ฐ˜๋‚ฉ์ด ์ด๋ฃจ์–ด์ง€์ง€ ์•Š๋Š” ๊ฒฝ์šฐ ๋ฉ”๋ชจ๋ฆฌ ๋ˆ„์ˆ˜๊ฐ€ ์ƒ๊ธธ ์ˆ˜ ์žˆ์œผ๋ฉฐ ๋‹ค๋ฅธ ํ”„๋กœ์„ธ์Šค, ์Šค๋ ˆ๋“œ์— ์˜ํ–ฅ์„ ์ค„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ finally ๋ธ”๋ก ๋‚ด์—์„œ ์ž์›์„ ํ•ด์ œํ•ด์•ผ ํ•œ๋‹ค.

์ž์›์„ ๋ฐ˜๋‚ฉํ•˜๋Š” ์ถ”๊ฐ€์ ์ธ ์ฝ”๋“œ๊ฐ€ ํ•„์š”ํ•˜๋ฉฐ ์‹ค์ˆ˜๋‚˜ ์—๋Ÿฌ๋กœ ์ž์›์„ ๋ฐ˜๋‚ฉํ•˜์ง€ ๋ชปํ•˜๋Š” ๊ฒฝ์šฐ๊ฐ€ ์ƒ๊ธธ ์ˆ˜ ์žˆ๋‹ค.

์ด๋Ÿฌํ•œ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด ์ž๋ฐ” 7 ๋ถ€ํ„ฐ ์ž์›์„ ์ž๋™์œผ๋กœ ๋ฐ˜๋‚ฉํ•ด์ฃผ๋Š” try-with-resources ๋ฌธ๋ฒ•์ด ๋„์ž…๋˜์—ˆ๋‹ค.




try-with-resources

try-with-resources ๋Š” Java7 ๋ถ€ํ„ฐ ๋„์ž…๋œ ์ž์› ๊ด€๋ฆฌ๋ฅผ ์œ„ํ•œ ๊ตฌ๋ฌธ์ด๋‹ค.

AutoClosable ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ตฌํ˜„ํ•˜๊ณ  ์žˆ๋Š” ์ž์›์„, ์‚ฌ์šฉ ํ›„ ์ž๋™์œผ๋กœ ๋ฐ˜๋‚ฉํ•ด์ฃผ๋Š” ๊ธฐ๋Šฅ์„ ์ œ๊ณตํ•œ๋‹ค.
์ด๋ฅผ ์‚ฌ์šฉํ•จ์œผ๋กœ์จ ๊ฐ€๋…์„ฑ์ด ์ข‹์•„์ง€๊ณ  ์˜ˆ์™ธ ๋ฐœ์ƒ ์‹œ ์ž์›์ด ์•ˆ์ „ํ•˜๊ฒŒ ํ•ด์ œ๋  ์ˆ˜ ์žˆ๋‹ค.

1
2
3
4
5
try (/*์ž์› ์ดˆ๊ธฐํ™”*/) {
  // ์ž์›์„ ์‚ฌ์šฉํ•˜๋Š” ์ฝ”๋“œ
} catch (์˜ˆ์™ธ ํƒ€์ž… ๋ณ€์ˆ˜) {
  // ์˜ˆ์™ธ ์ฒ˜๋ฆฌ ์ฝ”๋“œ
}



AutoCloseable ์ธํ„ฐํŽ˜์ด์Šค๋ฅผ ๊ตฌํ˜„ํ•œ ๊ฐ์ฒด๋งŒ try ๋ธ”๋ก ๋‚ด์—์„œ ๋ฆฌ์†Œ์Šค๋กœ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

์ฃผ๋กœ ํŒŒ์ผ, ์†Œ์ผ“, ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค ์—ฐ๊ฒฐ ๋“ฑ์— ์‚ฌ์šฉ๋ฉ๋‹ˆ๋‹ค.



Connection.java




Closeable๊ณผ AutoCloseable์˜ ๊ด€๊ณ„

๊ธฐ์กด์˜ Closeable ์— ๋ถ€๋ชจ ์ธํ„ฐํŽ˜์ด์Šค AutoCloseable ๋ฅผ ์ถ”๊ฐ€ํ•œ ํ˜•ํƒœ์ž…๋‹ˆ๋‹ค. Closeable์€ AutoCloseable์„ ํ™•์žฅํ•œ ํ•˜์œ„ ์ธํ„ฐํŽ˜์ด์Šค์ž…๋‹ˆ๋‹ค. ๋”ฐ๋ผ์„œ Closeable์€ AutoCloseable์ด ์ œ๊ณตํ•˜๋Š” ๋ชจ๋“  ๊ธฐ๋Šฅ์„ ํฌํ•จํ•ฉ๋‹ˆ๋‹ค. ์ด๋Ÿฌํ•œ ๊ตฌ์กฐ๋กœ ๊ธฐ์กด์— ๊ตฌํ˜„๋œ ์ž์› ํด๋ž˜์Šค ๋ชจ๋‘ try-with-resources ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.


  • try-catch ๋ฌธ์—์„œ๋Š” ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•  ์ˆ˜ ์žˆ๋Š” ๋ชจ๋“  ์ฝ”๋“œ๊ฐ€ ํฌํ•จ๋  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ํŠน์ • ๊ฐ์ฒด ํƒ€์ž…์— ์ œํ•œ๋˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

  • try-with-resources ๋ฌธ์—์„œ๋Š” AutoCloseable ๋ฅผ ๊ตฌํ˜„ํ•œ ๊ฐ์ฒด๋งŒ์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ, ๊ตฌ๋ฌธ์„ ์‚ฌ์šฉํ•˜๋ฉด ๋ฆฌ์†Œ์Šค ๋ˆ„์ˆ˜๋ฅผ ๋ฐฉ์ง€ํ•  ์ˆ˜ ์žˆ์–ด ์ž์› ๊ด€๋ฆฌ์— ๋งค์šฐ ์œ ์šฉํ•ฉ๋‹ˆ๋‹ค.

This post is licensed under CC BY 4.0 by the author.