定义自己的异常类的最佳做法? [英] Best practices for defining your own exception classes?
问题描述
最佳做法是什么?我应该从 std :: exception
或 std :: runtime_error
继承
是的,这是一个很好的做法,继承从 std :: runtime_error
或其他标准异常类,如 std :: logic_error
, std :: invalid_argument
等等,取决于哪种异常。
如果所有异常都从 std :: exception中继承
通过 catch(const std :: exception& e){...}
可以很容易地捕获所有常见的错误。如果你有几个独立的层次结构,这会变得更加复杂。从专门的异常类派生出来,这些异常会传递更多的信息,但是真正有用的取决于你如何处理异常。
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 inherit from std::exception
or std::runtime_error
?
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.
这篇关于定义自己的异常类的最佳做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!