Pau*_*cas 5 c++ exception-handling
我想调用一个可能抛出异常的函数。如果它确实抛出异常,我想捕获它并将异常对象传递给处理函数。处理程序函数的默认实现只是抛出异常。这是说明问题的精简代码:
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
exception_handler( e );
}
catch ( base_exception const &e ) {
cout << e.what() << endl; // prints "base_exception" due to object slicing
}
}
}
Run Code Online (Sandbox Code Playgroud)
但是,throw einexception_handler()会抛出异常的静态类型的副本,即base_exception. 我怎样才能exception_handler()抛出具有正确运行时类型的实际异常derived_exception?或者我怎样才能重新设计东西以获得我想要的东西?
您可以将throw_me虚函数放入异常基类中,并让每个派生类重写它。派生类可以抛出正确的最派生类型,而无需切片。尽管函数在每个类中具有相同的定义,但它们并不相同 - 每种情况下的类型都*this不同。
struct base_exception : exception
{
char const* what() const throw() { return "base_exception"; }
virtual void throw_me() const { throw *this; }
};
struct derived_exception : base_exception
{
char const* what() const throw() { return "derived_exception"; }
virtual void throw_me() const { throw *this; }
};
void exception_handler( base_exception const &e ) {
e.throw_me();
}
Run Code Online (Sandbox Code Playgroud)