定义自己的异常类的最佳实践? [英] Best practices for defining your own exception classes?
问题描述
我有一些特殊的异常情况,我想抛出和捕捉,所以我想定义自己的异常类。
I have some special exception cases that I want to throw and catch, so I want to define my own exception classes.
有哪些最佳实践?我应该继承 std :: exception
还是 std :: runtime_error
?
What are the best practices for that? Should I inherit from std::exception
or std::runtime_error
?
推荐答案
是的,良好的做法是继承 std :: runtime_error
或其他标准异常类,例如 std :: logic_error
, std :: invalid_argument
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.
如果所有的异常都继承了 std :: exception
的一些方法,通过 catch(const std :: exception& e){...}
捕获所有常见错误。如果你有几个独立的层次结构,这变得更复杂。从专门的异常类派生使这些异常携带更多的信息,但这真的有多有用取决于你如何处理你的异常。
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.
这篇关于定义自己的异常类的最佳实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!