C++ 速查手冊 V1.00 - 單元 6 範例




u06.cpp


1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
  
int main() {
   int a = 12
    
   std::cout << a << std::endl;
 
   return 0;
}
  
/* Kaiching Chang
   u06.cpp
   2014-02 */

u0601_1.cpp


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
 
int main() {
   int i = -1;
 
   try {
      if (i < 0) {
         throw "something wrong...";
      }
   }
   catch (const char* message) {
      std::cout << message
                << std::endl;
   }
 
   return 0;
}
  
/* Kaiching Chang
   u0601_1.cpp
   2014-02 */

u0601_2.cpp


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
 
struct BadValue :
public std::exception {};
 
double divide(double a, double b) {
   if (b == 0) {
      throw BadValue();
   }
 
   return a / b; 
}
 
int main() {
   try {
      std::cout << divide(20, 5)
                << std::endl;
      std::cout << divide(20, 4)
                << std::endl;
      std::cout << divide(20, 3)
                << std::endl;
      std::cout << divide(20, 2)
                << std::endl;
      std::cout << divide(20, 1)
                << std::endl;
      std::cout << divide(20, 0)
                << std::endl;
   }
   catch (BadValue e) {
      std::cout << "something wrong..."
                << std::endl;
   }
 
   return 0;
}
  
/* Kaiching Chang
   u0601_2.cpp
   2014-02 */

u0602.cpp


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
 
int main() {
   int i = -1;
 
   try {
      if (i > 0) {
         throw 0;
      }
      throw 2.0;
   }
   catch (const int e) {
      std::cout << e
                << std::endl;
   }
   catch (...) {
      std::cout << "something wrong"
                << std::endl;
   }
 
   return 0;
}
  
/* Kaiching Chang
   u0602.cpp
   2014-02 */

the end

沒有留言: