Best practices for defining your own exception classes?

前端 未结 5 769
走了就别回头了
走了就别回头了 2020-12-28 12:57

I have some special exception cases that I want to throw and catch, so I want to define my own exception classes.

What are the best practices for that? Should I inh

相关标签:
5条回答
  • 2020-12-28 13:39

    Yes, it's good practice to inherit from std::runtime_error or the other standard exception classes like std::logic_error, std::invalid_argument and so on, depending on which kind of exception it is.

    If all the exceptions inherit some way from std::exception it's easy to catch all common errors by a catch(const std::exception &e) {...}. If you have several independent hierarchies this gets more complicated. Deriving from the specialized exception classes makes these exceptions carry more information, but how useful this really is depends on how you do your exception handling.

    0 讨论(0)
  • 2020-12-28 13:39

    It is a good when exception is placed in some scope. For instance class Manipulation can declare inside exception classes Error.

    and catch them like

    catch ( const Manipulation::InputError& error )
    catch ( const Manipulation::CalculationError& error )
    

    In such cases they can be just empty classes without any additional error information unless you design allows those exceptions fly much upper where you catch all standard exceptions.

    0 讨论(0)
  • 2020-12-28 13:58

    In my opinion it doesn't matter if you inherit from std::exception or not. For me the most important thing about defining exceptions are:

    1. Having the exception class names be useful and clear.
    2. Clearly documenting (writing comments) when exception will get thrown by a function or class method. This is the single biggest failure point in exception handling in my opinion.
    0 讨论(0)
  • 2020-12-28 14:01

    I'm not a C++ developer, but one thing we did in our C# code was create a base class exception for our framework, and then log the exception thrown in the constructor:

      public FrameworkException(string message, Exception innerException)
          : base(message, innerException)
      {
          log.Error(message, innerException);
      }
    
      ...
    

    Any derived exception just has to invoke it's base constructor and we get consistent exception logging throughout. Not a big deal, but useful.

    0 讨论(0)
  • 2020-12-28 14:01

    It doesn't make a big difference, since std::runtime_error also inherits from std::exception. You could argue that runtime error conveys more information about the exception, but in practice, people often just derive from the base exception class.

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