8월 18, 2016

[EC++ 08] Prevent exceptions from leaving destructors.


C++은 최대 하나의 exception만 처리할 수 있음. 만약 두개 이상의 active exception이 동시에 발생하면 당시의 program 상황에 따라 premature program termination 또는 undefined behavior를 일으킴. dtor가 exception을 처리하지 않고 생략하면, dtor 과정에서 예외가 동시에 발생한 경우 premature program termination이나 undefined behavior를 일으킬 수 있음. dtor가 exception을 생략하는 것은 프로그램 실행 중 언제든 premature program termination이나 undefined behavior가 발생할 수 있어 위험함.

dtor에서 예외를 다루는 방법

  1. Terminate the program
  2. Swallow the exception
  3. Better strategy: 관련된 interface를 따로 정의하여 client가 발생가능한 문제에 대해 직접 대처할 수 있게 함.
  4. ex) DBConn::close() member method와 bool closed member field 를 정의.
    dtor가 수행하던 작업을 non-dtor function에게 이관하여 exception이 dtor에서 발생하는 것을 피할 수 있음. class 의 책임을 client에게 떠넘기는 것이라 볼 수도 있지만, 이런 방법을 통해 client에게 더 넓은 선택권을 제공할 수 있기에 좋은 방법임. client는 operation을 직접 수행하고 예외까지 직접 처리하여 더 안정된 프로그램을 구현할 수도 있고, operation을 dtor에게 맡기는 대신 다소간 프로그램의 불안정성을 감수하는 방법을 선택할 수도 있음.


Summary

  • Destructors should never emit exceptions. If functions called in a destructor may throw, the destructor should catch any exceptions, then swallow them or termainate the program.
  • If class clients need to be able to react to exceptions thrown during an operation, the class should provide a regular (i.e., non-destuctor) function that performs the operation.

Reference

  • Effective C++ by Scott Meyers

댓글 없음:

댓글 쓰기