The multiple or conditional catch C++ source code sample


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: Catching multiple exceptions

To show: The multiple or conditional catch in the try-catch-throw C++ code sample




// Exception: multiple catch blocks example

#include <iostream>

using namespace std;


int main(void)




char * teststr;

teststr = new char [10];

// test, if memory allocation fails then, throws this error to the matching catch...

if (teststr == NULL) throw "Allocation failure";

for (int i=0; i<15; i++)

// another test, if n>9, throw this error to the respective catch..

if (i>9) throw i;


cout<<"teststr["<<i<<"] = "<<teststr[i]<<endl> 9, by displaying some error message...

catch (int j)


cout<<"The exception: ";

cout<<"index "<<j<<" is out of range"<<endl;


// catch the error if, allocation fail for *teststr by displaying some error...

catch (char * strg)


cout<<"The exception: "<<strg<<endl;


return 0;



Output example:


teststr[0] = z

teststr[1] = z

teststr[2] = z

teststr[3] = z

teststr[4] = z

teststr[5] = z

teststr[6] = z

teststr[7] = z

teststr[8] = z

teststr[9] = z

The exception: index 10 is out of range

Press any key to continue . . .



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