在C ++中捕获基类和派生类异常
为了捕获基类和派生类的异常,那么我们需要将派生类的catch块放在基类之前。否则,将永远无法到达派生类的catch块。
算法
Begin
Declare 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 Exception Thus 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.
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短