프로그래밍에 관해 제가 좋아하는 글귀가 있습니다:

잘 돌아가는 프로그램을 짜기는 쉽지만
안 돌아가지 않는 프로그램을 짜기는 어렵다.

예외처리(Exception Handling)가 "잘 돌아가는 프로그램"을 너머서 "안 돌아가지 않는 프로그램"을 짜는 데에 어떤 역할을 하는지, Java의 예를 한 번 살펴봅시다.

Something getSomething() {
    if (...)
        return null;
    return something;
}

위와 같은 코드 보다는 아래와 같이 예외를 던지는 것이 좋습니다.

Something getSomething() throws SomeException {
    if (...)
        throw new SomeException(...);
    return something;
}

왜냐하면, 다음과 같이 사용하는 코드가 있을 때,

getSomething().getSomeOtherThing().doGoodThing();

예외처리를 위해서 null을 사용하는 전자는 다음과 같이 지저분해지지만,

something = getSomething();
if (something != null) {
    otherThing = something.getSomeOtherThing();
    if (otherThing != null) {
        otherThing.doGoodThing();
    } else {
        // some other thing’s wrong
    }
} else {
    // something’s wrong
}

예외를 사용하는 후자는 try-catch로만 감싸주면 되기 때문이죠.

try {
    getSomething().getSomeOtherThing().doGoodThing();
} catch (SomeException e) {
    // something’s wrong
} catch (OtherException e) {
    // some other thing’s wrong
}

"안 돌아가지 않는 프로그램"을 간결하게 짜려면 Exception을 잘 활용해야만 합니다. null을 애용하다보면 결국 모든 예외상황을 다 NullPointerException으로 뭉쳐버리는 꼴이 됩니다. 따라서 null을 돌려주기 보다는 Exception을 던지는 것이 대체로 좋은 선택입니다. Exception의 종류(class hierarchy)를 얼마나 다양하게 가져가고, 어디부터 class로 구별하며 어디까지는 메시지로 구별할 것인가는 또 다른 어려운 엔지니어링 문제입니다만, 어쨌든 Exception이 간결함에 유익하다는 사실은 변하지 않습니다. 일단 코드 덩어리가 팽창하기 시작하면 아무도 통제할 수 없는 괴물이 됩니다. 간결함의 미를 잃어버리는 순간 여러분은 진 겁니다.

Beauty is more important in computing than anywhere else in technology
because software is so complicated. Beauty is the ultimate defense against
complexity.

-- David Gelernter. "Machine Beauty: Elegance and the Heart of Technology
(1998)"

Sun의 Java 자습서는 Exception을 제대로 익히기 위한 훌륭한 자료이며, Java API 문서도 읽어볼만 합니다.


pgmg java

daybreaker

 그거 제대로 안 되어 있으면 http://blog.needlworks.org/ko/entry/%EC%98%88%EC%99%B8-%EC%B2%98%EB%A6%AC%EB%8A%94-%EC%96%B8%EC%A0%9C%EB%82%98-%ED%99%95%EC%8B%A4%ED%95%98%EA%B2%8C 이런 일이 벌어지기도 하지요...OTL

그나저나 여긴 트랙백 기능이 없나요;