Should I inherit from std::exception?

前端 未结 14 1436
有刺的猬
有刺的猬 2020-11-30 18:56

I\'ve seen at least one reliable source (a C++ class I took) recommend that application-specific exception classes in C++ should inherit from std::exception. I\

相关标签:
14条回答
  • 2020-11-30 19:31

    Reason for inheriting from std::exception is it "standard" base class for exceptions, so it is natural for other people on a team, for example, to expect that and catch base std::exception.

    If you are looking for convenience, you can inherit from std::runtime_error that provides std::string constructor.

    0 讨论(0)
  • 2020-11-30 19:32

    The main benefit is that code using your classes doesn't have to know exact type of what you throw at it, but can just catch the std::exception.

    Edit: as Martin and others noted, you actually want to derive from one of the sub-classes of std::exception declared in <stdexcept> header.

    0 讨论(0)
  • 2020-11-30 19:35

    Difference: std::runtime_error vs std::exception()

    Whether you should inherit from it or not is up to you. Standard std::exception and its standard descendants propose one possible exception hierarchy structure (division into logic_error subhierarchy and runtime_error subhierarchy) and one possible exception object interface. If you like it - use it. If for some reason you need something different - define your own exception framework.

    0 讨论(0)
  • 2020-11-30 19:36

    The problem with std::exception is that there is no constructor (in the standard compliant versions) that accepts a message.

    As a result I prefer to derive from std::runtime_error. This is derived from std::exception but its constructors allow you to pass a C-String or a std::string to the constructor that will be returned (as a char const*) when what() is called.

    0 讨论(0)
  • 2020-11-30 19:38

    You should inherit from boost::exception. It provides a lot more features and well-understood ways to carry additional data... of course, if you're not using Boost, then ignore this suggestion.

    0 讨论(0)
  • 2020-11-30 19:39

    If all your possible exceptions derive from std::exception, your catch block can simply catch(std::exception & e) and be assured of capturing everything.

    Once you've captured the exception, you can use that what method to get more information. C++ doesn't support duck-typing, so another class with a what method would require a different catch and different code to use it.

    0 讨论(0)
提交回复
热议问题