C ++构造函数引发的异常
这是从C++构造函数引发异常的简单示例
算法
类说明和伪代码:
Begin
Declare a class sample1.
Declare a constructor of sample1.
Print “Construct an Object of sample1”
Declare a destructor of sample1.
Print “Destruct an Object of sample1”
Declare a class sample.
Declare a constructor of sample2.
Declare variable i of the integer datatype.
Initialize i = 7.
Print “Construct an Object of sample1”.
Throw i.
Declare a destructor of sample2.
Print “Destruct an Object of sample2”
Try:
Declare an object s1 of class sample1.
Declare an object s2 of class sample2.
Catch(int i)
Print “Caught”.
Print the value of variable i
End.示例
#include <iostream>
using namespace std;
class Sample1 {
public:
Sample1() {
cout << "Construct an Object of sample1" << endl;
}
~Sample1() {
cout << "Destruct an Object of sample1" << endl;
}
};
class Sample2 {
public:
Sample2() {
int i = 7;
cout << "Construct an Object of sample2" << endl;
throw i;
}
~Sample2() {
cout << "Destruct an Object of sample2" << endl;
}
};
int main() {
try {
Sample1 s1;
Sample2 s2;
} catch(int i) {
cout << "Caught " << i << endl;
}
}输出结果
Construct an Object of sample1 Construct an Object of sample2 Destruct an Object of sample1 Caught 7
热门推荐
1 狗狗技能训练
5 如何训练狗狗笑
6 狗狗训练排便
9 狗狗响片训练
10 如何训练狗狗不捡食
11 狗狗尿训练
12 怎么训练狗狗找东西
13 狗狗训练站立
14 狗狗训练飞盘
15 鞍山狗狗训练
16 怎样训练泰迪狗狗谢谢
17 狗狗外出训练
18 怎么训练金毛狗狗大小便