在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 毕业祝福语简短给同学