The try-catch-throw 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: Using the try-catch-throw construct in C++ program

To show: The try-catch-throw construct flow in C++ source code






// A very simple try-throw-catch construct (C++)

#include <iostream>

using namespace std;


int main(void)


// declare char pointer

char* buff;

// try block...



// allocate storage for char object...

buff = new char[1024];

// do a test, if allocation fails...

if(buff == 0)

throw "Memory allocation failure!";

// if allocation successful, display the following message, bypass the catch block...


cout<<sizeof(buff)<<" Byte successfully allocated!"<<endl;


// if allocation fails, catch the type...

// display message...

catch(char* strg)


cout<<"Exception raised: "<<strg<<endl;


return 0;



Output example:


4 Byte successfully allocated!

Press any key to continue . . .


Then change the following code:


buff = new char[1024]; to buff = NULL;


Re-build and re-run the program. The following output should be expected.


Exception raised: Memory allocation failure!

Press any key to continue . . .



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