catch异常的常见误区
时间:2011-03-13 来源:studycpp
1,异常对象总是在抛出点创建。
1 //myException1.cpp
2 #include<iostream>
3 using namespace std;
4
5 class myException
6 {
7 public:
8 myException()
9 {
10 cout<<"default construct"<<endl;
11 }
12 myException(const myException& e)
13 {
14 cout<<"copy construct"<<endl;
15 }
16 myException operator= (const myException& e)
17 {
18 cout<<"assign construct"<<endl;
19 }
20 void printMsg()
21 {
22 cout<<"myException detail massage"<<endl;
23 }
24 };
25
26
27 int main(int agc, char** argv)
28 {
29 try
30 {
31 myException e;
32 throw e;
33 }
34 catch (myException &e)
35 {
36 e.printMsg();
37
38 return -1;
39 }
40 return 0;
41 }
42
43
编译,运行
$ ./test.exe
default construct
copy construct
myException detail massage
可以看出,调用了拷贝构造,说明throw e;实际不是跑出e对象,而是其一份拷贝。
正确的是
1 int main(int agc, char** argv)
2 {
3 try
4 {
5 //myException e;
6 throw myException();
7 }
8 catch (myException &e)
9 {
10 e.printMsg();
11
12 return -1;
13 }
14 return 0;
15 }
执行结果如下
$ ./test.exe
default construct
myException detail massage
2,catch 的异常声明中异常对象要被声明为引用
如下非引用
1 int main(int agc, char** argv)
2 {
3 try
4 {
5 //myException e;
6 throw myException();
7 }
8 catch (myException e)
9 {
10 e.printMsg();
11
12 return -1;
13 }
14 return 0;
15 }
执行结果$ ./test.exe
default construct
copy construct
myException detail massage
相关阅读 更多 +
排行榜 更多 +