Rev | Line | |
---|
[5442] | 1 | // This example illustrates rethrowing an exception.
|
---|
| 2 |
|
---|
| 3 | #include <stdlib.h>
|
---|
| 4 | #include <iostream.h>
|
---|
| 5 | class FileIO
|
---|
| 6 | {
|
---|
| 7 | public:
|
---|
| 8 | int reason1;
|
---|
| 9 | int reason2;
|
---|
| 10 | FileIO() {reason1 = reason2 = 0;}; // initialize data members
|
---|
| 11 |
|
---|
| 12 | // the following member function throws an exception
|
---|
| 13 | void foo(int arg) {
|
---|
| 14 | FileIO fio;
|
---|
| 15 |
|
---|
| 16 | // throw different exception depending on arg
|
---|
| 17 | switch (arg)
|
---|
| 18 | {
|
---|
| 19 | case 1:
|
---|
| 20 | fio.reason1 = 1;
|
---|
| 21 | break;
|
---|
| 22 | case 2:
|
---|
| 23 | fio.reason2 = 1;
|
---|
| 24 | break;
|
---|
| 25 | }
|
---|
| 26 | throw fio;
|
---|
| 27 | };
|
---|
| 28 | };
|
---|
| 29 | // .
|
---|
| 30 | // .
|
---|
| 31 | // .
|
---|
| 32 | void f(int arg)
|
---|
| 33 | {
|
---|
| 34 | FileIO fio;
|
---|
| 35 | try
|
---|
| 36 | {
|
---|
| 37 | // call member functions of FileIO class
|
---|
| 38 | fio.foo(arg);
|
---|
| 39 | }
|
---|
| 40 |
|
---|
| 41 | catch(FileIO fexc)
|
---|
| 42 | {
|
---|
| 43 | if (fexc.reason1)
|
---|
| 44 | cout << "Exception #1" << endl;
|
---|
| 45 | else if (fexc.reason2)
|
---|
| 46 | cout << "Exception #2" << endl;
|
---|
| 47 | else
|
---|
| 48 | throw; // rethrow to outer handler
|
---|
| 49 | }
|
---|
| 50 | catch(...) { /* ... */ } // catch other exceptions
|
---|
| 51 | }
|
---|
| 52 |
|
---|
| 53 | void main(int argc, char **argv)
|
---|
| 54 | {
|
---|
| 55 | int arg = 0;
|
---|
| 56 |
|
---|
| 57 | if (argc == 2)
|
---|
| 58 | {
|
---|
| 59 | arg = atoi(argv[1]);
|
---|
| 60 | }
|
---|
| 61 |
|
---|
| 62 | try
|
---|
| 63 | {
|
---|
| 64 | f(arg);
|
---|
| 65 | }
|
---|
| 66 | catch(FileIO)
|
---|
| 67 | {
|
---|
| 68 | cout << "Outer Handler" << endl;
|
---|
| 69 | }
|
---|
| 70 |
|
---|
| 71 | cout << "Finished." << endl;
|
---|
| 72 | }
|
---|
Note:
See
TracBrowser
for help on using the repository browser.