在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.
热门推荐
1 带狗狗训练
4 听力训练狗狗
6 怎训练狗狗
7 腹肌训练狗狗
8 网球训练狗狗
9 记叙文训练狗狗
10 狗狗太凶怎么训练
11 核心力量训练狗狗
12 狗狗乱叫怎么训练
13 发音训练狗狗
14 怎么训练狗狗叼东西给主人
15 荆州训练狗狗
16 篮球训练狗狗
17 做训练狗狗
18 训练狗狗坐姿