The exception handling: the try-catch and __try __finally constructs

 

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: Using the try-catch and __try __finally constructs

To show: The exception handling in C program flow: the try-catch and try-finally constructs

 

// C/C++ structured exception handling and C++ exception handling.

#include <iostream>

using namespace std;

 

// function prototype...

void TestCFunct(void);

 

int main(void)

{

// C++ try block...

try

{

//function calls...

TestCFunct();

}

// catch block...

catch(...)

{

cout<<"Caught the exception, C style..."<<endl;

}

return 0;

}

 

// function definition...

void TestCFunct()

{

// structured handling exception...

__try

{

int p, r = 2, q = 1;

// exception should be raised here if divide by 0...

p = r*(10/q);

}

// else...

__finally

{

cout<<"In __finally - Look likes no exception lor!"<<endl;

// finding the appropriate catch...

}

}

 

Output example:

 

In __finally - Look likes no exception lor!

Press any key to continue . . .

 

Then change the value of q to 0. Recompile and re-run the program. Before the __finally execution, your compiler should generate and display Application Error box with "The exception Integer division by zero" message.

 

 

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