C++ C++;基类中的异常处理
假设我有一些通用的应用程序类定义,其中包含:C++ C++;基类中的异常处理,c++,inheritance,exception-handling,C++,Inheritance,Exception Handling,假设我有一些通用的应用程序类定义,其中包含: class Application{ public: void Run(){ try{ .... }catch(const Exception& ex){ .... } } 现在假设我从类App1继承应用程序: class App1: public Application{ void Run(){ Appl
class Application{
public:
void Run(){
try{
....
}catch(const Exception& ex){
....
}
}
现在假设我从类App1继承应用程序:
class App1: public Application{
void Run(){
Application::Run();
throw ex;
}
}
是否有方法捕获基类中的异常?我试过上面的方法,但不起作用。不,你不能。当你
抛出ex时
在App1:Run()
中,Application::Run()
已完成运行。使用虚拟函数,如下所示:
class Application{
public:
virtual void DoRun() {
....
}
void Run(){
try{
DoRun();
}catch(const Exception& ex){
....
}
}
class App1: public Application{
virtual void DoRun() {
Application::DoRun();
throw ex;
}
}
我会让
DoRun
受到保护,以强调Run
是代码之外应该使用的。