我想调用一个可能抛出异常的函数。如果它确实抛出异常,我想捕获它并将异常对象传递给处理函数。处理程序函数的默认实现只是抛出异常。这是说明问题的精简代码:
struct base_exception : exception {
char const* what() const throw() { return "base_exception"; }
};
struct derived_exception : base_exception {
char const* what() const throw() { return "derived_exception"; }
};
void exception_handler( base_exception const &e ) {
throw e; // always throws a base_exception object even if e is a derived_exception
}
int main() {
try {
throw derived_exception();
}
catch ( base_exception const &e ) {
try {
cout << e.what() << endl; // prints "derived_exception" as expected …Run Code Online (Sandbox Code Playgroud) 在读取异常时,我知道在抛出对象时,总是基于静态类型信息构造对象。如果发生异常,我们如何抛出子类对象?以下是《更有效的C ++》一书中的几行内容:
Run Code Online (Sandbox Code Playgroud)class Widget{...}; class SpecialWidget: public Widget {...}; void passAndThrowWidget() { SpecialWidget localSpecialWidget; ... Widget& rw = localSpecialWidget; throw rw; // this throws an exception of type widget! }即使rw指向,也会在此处引发Widget异常
SpecialWidget。那是因为rw的静态类型是Widget,而不是Special-Widget。rw实际上是指SpecialWidget,您的编译器并不关心。他们只关心rw的静态类型。
这就解释了为什么会发生这种情况,但没有提供解决问题的方法。