The exception (handling), class and destructor C++ program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info:

To do: try, catch and throw an exception

To show: The exception, class and destructor relationship in C++ code

 

// Exception, class and destructor

#include <iostream>

using namespace std;

 

void TestFunct(void);

 

// class Test1 declaration...

class Test1

{

public:

Test1(){};

~Test1(){};

 

const char *TestShow() const

{

cout<<"In class member function *TestShow():\n";

return " Exception in Test1 class.";

}

};

 

// another class declaration, DestrTest...

class DestrTest

{

public:

DestrTest();

~DestrTest();

};

 

// constructor class implementation

DestrTest::DestrTest()

{

cout<<"Next, in constructor DestrTest():\n";

cout<<" Constructing the DestrTest...\n";

}

 

// destructor class implementation

DestrTest::~DestrTest()

{

cout<<"Next, in destructor ~DestrTest():\n";

cout<<" Destructing the DestrTest...\n";

}

 

void TestFunct()

{

// instantiate an object, constructor invoked...

DestrTest p;

cout<<"Next in TestFunct(): \n Throwing Test1 type exception...\n";

// first throw...

throw Test1();

}

 

int main(void)

{

cout<<"Starting in main()...\n";

try

{

cout<<"Now, in the try block: \n Calling TestFunct()...\n";

TestFunct();

}

 

// instantiate another object, constructor invoked...

catch(Test1 q)

{

cout<<"Next, in catch handler:\n";

cout<<" Caught Test1 type exception...\n";

cout<<q.TestShow()<<"\n";

}

catch(char *strg)

{

cout<<"Caught char pointer type exception: "<<strg<<"\n";

}

cout<<"Back in main...\n";

return 0;

}

 

Output example:

 

Starting in main()...

Now, in the try block:

Calling TestFunct()...

Next, in constructor DestrTest():

Constructing the DestrTest...

Next in TestFunct():

Throwing Test1 type exception...

Next, in destructor ~DestrTest():

Destructing the DestrTest...

Next, in catch handler:

Caught Test1 type exception...

In class member function *TestShow():

Exception in Test1 class.

Back in main...

Press any key to continue . . .

 

 

C and C++ Programming Resources | C & C++ Code Example Index