Best practices for defining your own exception classes?

前端 未结 5 768
走了就别回头了
走了就别回头了 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.

提交回复
热议问题