在C ++中捕获基类和派生类异常
为了捕获基类和派生类的异常,那么我们需要将派生类的catch块放在基类之前。否则,将永远无法到达派生类的catch块。
算法
BeginDeclare a class B.
Declare another class D which inherits class B.
Declare an object of class D.
Try: throw derived.
Catch (D derived)
Print “Caught Derived Exception”.
Catch (B b)
Print “Caught Base Exception”.
End.
这是一个简单的示例,其中将派生类的捕获放置在基类的捕获之前,现在检查输出
#include<iostream>using namespace std;
class B {};
class D: public B {}; //class D inherit the class B
int main() {
D derived;
try {
throw derived;
}
catch(D derived){
cout<<"Caught Derived Exception"; //catch block of derived class
}
catch(B b) {
cout<<"Caught Base Exception"; //catch block of base class
}
return 0;
}
输出结果
Caught Derived Exception
这是一个简单的示例,其中基类的捕获已放置在派生类的捕获之前,现在检查输出
#include<iostream>using namespace std;
class B {};
class D: public B {}; //class D inherit the class B
int main() {
D derived;
try {
throw derived;
}
catch(B b) {
cout<<"Caught Base Exception"; //catch block of base class
}
catch(D derived){
cout<<"Caught Derived Exception"; //catch block of derived class
}
return 0;
}
输出结果
Caught Base ExceptionThus it is proved that we need to put catch block of derived class before the base class. Otherwise, the catch block of derived class will never be reached.
以上是 在C ++中捕获基类和派生类异常 的全部内容, 来源链接: utcz.com/z/358725.html