How to throw good exceptions?

前端 未结 12 1403
情话喂你
情话喂你 2020-12-14 21:05

I heard you should never throw a string because there is a lack of information and you\'ll catch exceptions you dont expect to catch. What are good practice for throwing exc

12条回答
  •  北荒
    北荒 (楼主)
    2020-12-14 21:56

    You should always throw an exception class derived from std::exception. This allows a certain consistency to your interface and allows more flexibility to the clients of these methods or functions. For example if you want to add a catch all handler you may be able to add a

    catch(std::exception& e)
    block and be done with it. (Though often you won't be able to get away with that if you don't control all the code that can throw).

    I tend to throw only exceptions provided by the the standard (i.e. std::runtime_error) but if you want to provide extra granularity to your handlers, you should feel free to derive your own from std::exception. See the C++ FAQ lite.

    Also, you should throw a temporary and catch it by reference (to avoid the copy ctor be invoked at your catch site). Throwing pointers is also frowned upon since it is unclear who should clean up the memory. C++ FAQ Lite deals with this too.

提交回复
热议问题