Item 73. Abstraction Level Exceptions
์ถ์ํ ์์ค์ ๋ง๋ ์์ธ๋ฅผ ๋์ง๋ผ
์ํํ๋ ค๋ ์ผ๊ณผ ๊ด๋ จ ์์ด ๋ณด์ด๋ ์์ธ๊ฐ ๋ฐ์ํ๋ฉด ์ด๋ค ์๋ฌ๊ฐ ๋ฐ์ํ๋์ง ์๊ธฐ ์ด๋ ค์์ง๋ค.
์์ธ ๋ฒ์ญ(exception translation)
์์ ๊ณ์ธต์์ ์ฌ์ฉํ ๋, ์ ์์ค ์์ธ๋ฅผ ์ก์ ์์ ์ ์์ค์ ๋ง๋ ์์ธ๋ก ๋ฐ๊ฟ ๋์ง๋ ์์ธ ๋ฒ์ญ(exception translation) ๊ธฐ๋ฒ์ ์ฌ์ฉํ์ฌ ์๋ฌ ํ์ ์ ์ฝ๊ฒ ํ ์ ์๋ค.
class Example {
public static void main(String[] args) {
try {
// ...
} catch (LowerLevelException e) {
// ์ถ์ํ ์์ค์ ๋ง๊ฒ ๋ค๋ฅธ ์์ธ๋ก ์ ํ
throw new HigherLevelException();
}
}
}
์ค์ ๋ก AbstractSequentialList
์ get
๋ฉ์๋๋ ์๋์ ๊ฐ์ด ๊ตฌํ๋์ด ์๋ค.
public abstract class AbstractSequentialList<E> extends AbstractList<E> {
public E get(int index) {
try {
return listIterator(index).next();
} catch (NoSuchElementException exc) {
throw new IndexOutOfBoundsException("Index: " + index);
}
}
}
์์ธ ์ฐ์(exception chaining)
๋ง์ฝ ์ ์์ค ์์ธ๊ฐ ์ ์ฉํ ์ ๋ณด๋ฅผ ๋ด๊ณ ์๋ค๋ฉด, ์์ธ ์ฐ์(exception chaining) ๊ธฐ๋ฒ์ ์ฌ์ฉํ์ฌ ์์ธ ์ฐ๊ฒฐ์ ํตํด ์ ์์ค ์์ธ์ ์ ๋ณด๋ฅผ ๊ณ ์์ค ์์ธ์ ๋ด์์ ๋์ง๋ ๋ฐฉ๋ฒ๋ ์๋ค.
class Example {
public static void main(String[] args) {
try {
// ...
} catch (LowerLevelException cause) {
// ์ ์์ค ์์ธ๋ฅผ ๊ณ ์์ค ์์ธ์ ์ค์ด ๋ณด๋
throw new HigherLevelException(cause);
}
}
}
์์ ๊ฐ์ด ์ค์ด๋ณด๋ด๊ฒ ๋๋ฉด getCause
๋ฉ์๋๋ฅผ ํตํด ์ ์์ค ์์ธ๋ฅผ ํ์ธํ ์ ์์ด, ์์ธ๊ณผ ๊ณ ์์ค ์์ธ์ ์คํ ์ถ์ ์ ๋ณด๋ฅผ ๋ชจ๋ ํ์ธํ ์ ์๊ฒ ๋๋ค.
Last updated
Was this helpful?