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?