ํค์๋ throw๋ฅผ ์ฌ์ฉํด์ ํ๋ก๊ทธ๋๋จธ๊ฐ ๊ณ ์๋ก ์์ธ๋ฅผ ๋ฐ์์ํฌ ์ ์๋ค.
๋ฐฉ๋ฒ
1 . ์ฐ์ฐ์ new๋ฅผ ์ด์ฉํด์ ๋ฐ์์ํค๋ ค๋ ์์ธ ํด๋์ค์ ๊ฐ์ฒด๋ฅผ ๋ง๋ ๋ค.
Exception e= new Exception("๊ณ ์๋ก ๋ฐ์์ํด");
2 . ํค์๋ throw๋ฅผ ์ด์ฉํด์ ์์ธ๋ฅผ ๋ฐ์์ํจ๋ค.
throw e
์๋ ์์์ฒ๋ผ throw new Exception("๊ณ ์๋ก ๋ฐ์์์ผฐ์.") ์ฒ๋ผ ํ์ค๋ก ์์ธ ๋ฐ์์ํค๊ณ ๋์ง๋ ๊ฒ์ ๋ ๋ง์ด ์ฌ์ฉํ๋ค.
class Tes {
public static void main(String[] args) {
try {
Exception e = new Exception("๊ณ ์๋ก ๋ฐ์์์ผฐ์.");
throw e; // ์์ธ๋ฅผ ๋ฐ์์ํด
// throw new Exception("๊ณ ์๋ก ๋ฐ์์์ผฐ์."); // ์ ๋ ์ค์ ํ ์ค๋ก ์์ฑ
} catch(Exception e) {
System.out.println("์๋ฌ ๋ฉ์์ง : " + e.getMessage());
e.printStackTrace();
}
System.out.println("ํ๋ก๊ทธ๋จ์ด ์ ์ ์ข
๋ฃ๋์์.");
}
}
throw๋ ์์ธ๋ฅผ ์์ฑํ๋ ํค์๋๋ผ๋ ๊ฒ์ ์์๋ค. ํ์ง๋ง ๋น์ทํ๊ฒ ์๊ธด throws๋ ์์ ๋ค๋ฅธ ์ญํ ์ธ ์์ธ๋ฅผ ์ฒ๋ฆฌํ๋ ๋ฐฉ๋ฒ ์ค ํ๋๋ค.
์์ธ๋ฅผ ์ฒ๋ฆฌํ๋ ๋ฐฉ๋ฒ์ ๋ค์ 2๊ฐ์ง ๋ฐฉ๋ฒ์ด ์๋ค.
๋ฐฉ๋ฒ
์์ธ๊ฐ ์ฌ๋ฌ ๊ฐ์ธ ๊ฒฝ์ฐ ์ผํ(,)๋ก ๊ตฌ๋ถํ๋ค.
void method() throws Exception1, Exception2, ... ExceptionN {
// ๋ฉ์๋์ ๋ด์ฉ
}
๋ง์ฝ ์๋์ ๊ฐ์ด ๋ชจ๋ ์์ธ์ ์ต๊ณ ์กฐ์์ธ Exception ํด๋์ค๋ฅผ ๋ฉ์๋์ ์ ์ธํ๋ฉด, ์ด ๋ฉ์๋๋ ๋ชจ๋ ์ข ๋ฅ์ ์์ธ๊ฐ ๋ฐ์ํ ๊ฐ๋ฅ์ฑ์ด ์๋ค๋ ๋ป
void method() throws Exception {
// ๋ฉ์๋์ ๋ด์ฉ
}
class ExceptionEx14 {
public static void main(String[] args) {
try {
method1();
} catch (Exception e) {
System.out.println("main๋ฉ์๋์์ ์์ธ๊ฐ ์ฒ๋ฆฌ๋์์ต๋๋ค.");
e.printStackTrace();
}
} // main๋ฉ์๋์ ๋
static void method1() throws Exception {
throw new Exception();
} // method1()์ ๋
} // class์ ๋