๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿš— Major Study (Bachelor)/๐ŸŸ  JAVA Programming

JAVA ํ”„๋กœ๊ทธ๋ž˜๋ฐ 9.2

by UKHYUN22 2021. 11. 2.
728x90

Defining your own Exception classes

 

constructors

 

์‚ฌ์šฉ์ž๊ฐ€ ๋งŒ๋“  exception์€ Exception ํด๋ž˜์Šค์˜ child Class ๋ผ๋Š” ๊ฒƒ์„ ๊ผญ ๊ธฐ์–ตํ•˜๊ธฐ

์šฐ๋ฆฌ๊ฐ€ ํ•  ๊ฒƒ์€ Constructor๋งŒ ๋งŒ๋“œ๋Š” ๊ฒƒ์ด๋‹ค!!

 

 

Exception์„ ์ƒ์„ฑํ•ด ๋˜์ง€๊ฒŒ ๋˜๋Š” ๋ฌธ์ž์—ด์€ Object์•ˆ์— ์กด์žฌํ•˜๋Š” instance ๋ณ€์ˆ˜์— ์ €์žฅ์ด ๋˜๊ณ  getMessage ๋ฉ”์†Œ๋“œ๋ฅผ ํ†ตํ•ด์„œ ๋ฆฌํ„ด์„ ํ•˜๊ฒŒ ๋œ๋‹ค.

 

 

general ํ•˜๊ฒŒ ๋ฏธ๋ฆฌ ์ž‘์„ฑ๋œ Exception์œผ๋กœ ๋˜์ง€๊ฒŒ ๋˜๋ฉด catch block์—์„œ general ํ•œ Exception์œผ๋กœ ๋ฐ›๊ณ 

๋งŒ์•ฝ ์‚ฌ์šฉ์ž๊ฐ€ ์ž‘์„ฑํ•œ Exception์œผ๋กœ ๋˜์ง€๋ฉด ์‚ฌ์šฉ์ž๊ฐ€ ์ž‘์„ฑํ•œ specifical ํ•œ exception ์œผ๋กœ ๋ฐ›์œผ๋ฉด ๋œ๋‹ค.

์—ฌ๊ธฐ์„œ๋„ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ "Is a relation"์ด ์„ฑ๋ฆฝํ•œ๋‹ค,

์‚ฌ์šฉ์ž๊ฐ€ ์ž‘์„ฑํ•œ Specify๋œ exception์œผ๋กœ ๋˜์ง€๊ณ  generalํ•œ Exception์œผ๋กœ ๋ฐ›๊ฒŒ ๋˜๋„ ์„ฑ๋ฆฝํ•œ๋‹ค๋Š” ์–˜๊ธฐ

 

 

์„ฑ๋ฆฝํ•˜๋Š” ๊ฒฝ์šฐ

 

 

 

JVM, program, JVM

 

Error๋Š” Throwable์˜ subClass์ด๊ณ  Java Virtual Machine์—์„œ throw ํ•ด์ค€๋‹ค.

Exception์€ program์— ์˜ํ•ด์„œ throw ํ•ด์ง€๊ณ  ์‚ฌ์šฉ์ž๊ฐ€ ๋งŒ๋“  ๋ชจ๋“  exception์€ Exception ์˜ sub class ๊ฐ€ ๋œ๋‹ค.

RuntimeException์€ JVM์— ์˜ํ•ด์„œ throw๋˜๊ณ  Exception์˜ subClass์ด๋‹ค.

 

 

 

 

Unchecked Exception

: ์ปดํŒŒ์ผ์„ ํ•  ๋•Œ error์ธ์ง€ error๊ฐ€ ์•„๋‹Œ์ง€ ์ฒดํฌํ•˜์ง€ ์•Š๋Š”๋‹ค. ์ฆ‰, error์™€ run-time exception์— ํ•ด๋‹นํ•˜๋Š” ์—๋Ÿฌ๋“ค์€ ์ปดํŒŒ์ผ๋Ÿฌ๊ฐ€ ์ฒดํฌ๋ฅผ ํ•˜์ง€ ์•Š๋Š”๋‹ค. ์—๋Ÿฌ๊ฐ€ ์žˆ์–ด๋„ ๊ทธ๋ƒฅ ๋„˜์–ด๊ฐ€๊ฒŒ ๋œ๋‹ค.

 

Checked Exception

: ์ปดํŒŒ์ผ๋Ÿฌ๊ฐ€ ์ฒดํฌ๋ฅผ ํ•˜๊ณ  ์—๋Ÿฌ๊ฐ€ ์žˆ์œผ๋ฉด ๋ฐ”๋กœ ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๋ฅผ ๋•Œ๋ฆฐ๋‹ค."must be caught or declared in the throw clause" ์—๋Ÿฌ๋ฌธ์ด ๋œฌ๋‹ค. ๊ฐ€์žฅ ๋Œ€ํ‘œ์ ์ธ ๊ฒƒ์ด IOException์ด๋‹ค.

 

 

 

Unchecked Exception

 

Checked Exception

 

 

throws๊ฐ€ ์žˆ๋‹ค๋ฉด ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์ธก์—์„œ ๋ฐ˜๋“œ์‹œ try-catch๋ฅผ ์ง„ํ–‰ํ•ด์„œ ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑํ•ด์•ผ ํ•œ๋‹ค. ์ด๊ฒƒ์„ Checked Exception์ด๋ผ๊ณ  ํ•œ๋‹ค.

 

 

NumberformatException์ด ๋ฐœ์ƒํ•œ๋‹ค.

run-time error์ด๊ณ  ์ปดํŒŒ์ผ์„ ํ• ๋•Œ ์—๋Ÿฌ๋ฅผ ์žก์•„๋‚ด์ง€ ๋ชปํ•˜์ง€๋งŒ ๋‹ค๋ฅธ ํ˜•์‹์ด ์ฃผ์–ด์ง€๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์€ ์—๋Ÿฌ ๋ฉ”์‹œ์ง€๋ฅผ ์ถœ๋ ฅํ•˜๊ฒŒ ๋œ๋‹ค.

 

๋‹ค์Œ๊ณผ ๊ฐ™์ด catch block์—์„œ ์—๋Ÿฌ๋ฉ”์‹œ์ง€ ๋ฌธ์žฅ์„ ๋ฐ”๊พผ๋‹ค๋ฉด ์—๋Ÿฌ์ฐฝ์— ๋œจ๋Š” ๋ฉ”์‹œ์ง€๋ฅผ ๋ฐ”๊ฟ€ ์ˆ˜ ์žˆ๋‹ค.