捕獲異常,用引用還是用指針,我一直很糊涂。
學STL里面,有可能拋出異常的地方,用指針一直都無法捕獲,搞相當疑惑。
后來才知道,用那種格式需要對你調用函數(shù)會拋出哪種異常清楚才行。
下面是示例代碼:
1 #include <iostream>
2 #include <string>
3 #include <exception>
4
5 using std::cout;
6 using std::endl;
7 using std::string;
8 using std::exception;
9
10 class MyException : public exception{
11 public:
12 MyException();
13 };
14
15 MyException::MyException():exception("You know that"){}
16
17 void thr(){
18 throw new MyException();
19 }
20
21 void test_exception(){
22
23 string s;
24 try{
25 s.at(1);
26 }
27 catch(exception & e){
28 cout << "Caught exception." << e.what() << endl;
29 }
30
31 try{
32 thr();
33 }
34 catch(MyException* e){
35 cout << "Caught myException: " << e->what() << endl;
36 delete e;
37 e = NULL;
38 }
39 }
40
41 void main(){
42 test_exception();
43 }
44
異常是以指針方式拋出,就用指針形式來捕獲,用普通形式拋出,就需要用普通格式,為了減少復制,那么用引用就可以了。