我应该从std :: exception继承吗? [英] Should I inherit from std::exception?
问题描述
我已经看到至少一个可靠的源代码(一个C ++类)推荐C ++中的应用程序特定的异常类应该继承自 std :: exception
。我不清楚这种方法的好处。
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'm not clear on the benefits of this approach.
在C#中继承 ApplicationException
的原因很清楚:你会得到一些有用的方法,属性和构造函数,只需要添加或覆盖你需要的。使用 std :: exception
看来,你得到的是一个 what()
覆盖的方法,你可以
In C# the reasons for inheriting from ApplicationException
are clear: you get a handful of useful methods, properties and constructors and just have to add or override what you need. With std::exception
it seems that all you get is a what()
method to override, which you could just as well create yourself.
因此,如果使用 std :: exception
作为我的应用程序特定的异常类的基类?是否有任何好的理由不继承 std :: exception
?
So what are the benefits, if any, of using std::exception
as a base class for my application-specific exception class? Are there any good reasons not to inherit from std::exception
?
推荐答案
主要好处是使用你的类的代码不必知道你 throw
的确切类型,但可以 catch
std :: exception
。
编辑:如Martin和其他人所说,你其实想从 std的子类派生: :在
< stdexcept>
标题中声明。
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
.
as Martin and others noted, you actually want to derive from one of the sub-classes of std::exception
declared in <stdexcept>
header.
这篇关于我应该从std :: exception继承吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!