12
Exceptions
- #include <iostream>
- using namespace std;
- void MyFunc( void );
- class CTest
- {
- public:
- CTest();
- ~CTest();
- const char *ShowReason() const { return "Exception in CTest class."; }
- };
- CTest::CTest()
- {
- cout << "Constructing CTest." << endl;
- }
- CTest::~CTest()
- {
- cout << "Destructing CTest." << endl;
- }
- class CDtorDemo
- {
- public:
- CDtorDemo();
- ~CDtorDemo();
- };
- CDtorDemo::CDtorDemo()
- {
- cout << "Constructing CDtorDemo." << endl;
- }
- CDtorDemo::~CDtorDemo()
- {
- cout << "Destructing CDtorDemo." << endl;
- }
- void MyFunc()
- {
- CDtorDemo D;
- cout<< "In MyFunc(). Throwing CTest exception." << endl;
- throw CTest();
- }
- int main()
- {
- cout << "In main." << endl;
- try
- {
- cout << "In try block, calling MyFunc()." << endl;
- MyFunc();
- }
- catch( CTest E )
- {
- cout << "In catch handler." << endl;
- cout << "Caught CTest exception type: ";
- cout << E.ShowReason() << endl;
- }
- catch( char *str )
- {
- cout << "Caught some other exception: " << str << endl;
- }
- cout << "Back in main. Execution resumes here." << endl;
- return 0;
- }
- #include <iostream>
- #include <cstdlib>
- using namespace std;
- void term_func()
- {
- //...
- cout << "term_func was called by terminate." << endl;
- exit( -1 );
- }
- int main()
- {
- try
- {
- // ...
- set_terminate( term_func );
- // ...
- throw "Out of memory!"; // No catch handler for this exception
- }
- catch( int )
- {
- cout << "Integer exception raised." << endl;
- }
- return 0;
- }
- #include <iostream>
- using namespace std;
- void SEHFunc( void );
- int main()
- {
- try
- {
- SEHFunc();
- }
- catch( ... )
- {
- cout << "Caught a C exception." << endl;
- }
- return 0;
- }
- void SEHFunc()
- {
- __try
- {
- int x, y = 0;
- x = 5 / y;
- }
- __finally
- {
- cout << "In finally." << endl;
- }
- }
Commentaires