1 /* C++ exception handling example
2 
3    This example code is in the Public Domain (or CC0 licensed, at your option.)
4 
5    Unless required by applicable law or agreed to in writing, this
6    software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
7    CONDITIONS OF ANY KIND, either express or implied.
8 */
9 
10 #include <iostream>
11 
12 using std::cout;
13 using std::endl;
14 using std::runtime_error;
15 
16 /* A simple class which may throw an exception from constructor */
17 class Throwing
18 {
19 public:
Throwing(int arg)20     Throwing(int arg)
21     : m_arg(arg)
22     {
23         cout << "In constructor, arg=" << arg << endl;
24         if (arg == 0) {
25             throw runtime_error("Exception in constructor");
26         }
27     }
28 
~Throwing()29     ~Throwing()
30     {
31         cout << "In destructor, m_arg=" << m_arg << endl;
32     }
33 
34 protected:
35     int m_arg;
36 };
37 
38 /* Inside .cpp file, app_main function must be declared with C linkage */
app_main(void)39 extern "C" void app_main(void)
40 {
41     cout << "app_main starting" << endl;
42 
43     try {
44         /* This will succeed */
45         Throwing obj1(42);
46 
47         /* This will throw an exception */
48         Throwing obj2(0);
49 
50         cout << "This will not be printed" << endl;
51     } catch (const runtime_error &e) {
52         cout << "Exception caught: " << e.what() << endl;
53     }
54 
55     cout << "app_main done" << endl;
56 }
57