The exception (handling) specification implementation in C++

 

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-throw with caught exception

To show: The exception (handling) specification C++ program example demonstrating the try-catch-throw construct

 

// Exception specification

#include <iostream>

using namespace std;

 

// handler function

void handler()

{cout<<"In the handler()\n";}

 

// int throw...

void Funct1(void) throw(int)

{

static int x = 1;

cout<<"Funct1() call #"<<x++<<endl;

cout<<"About to throw 1\n";

if (1)

throw 1;

}

 

// empty throw...

void Funct5(void) throw()

{

try

{Funct1();}

catch(...)

{handler();}

}

 

// invalid, doesn't handle the int exception thrown from Funct1()

// void Funct3(void) throw()

// {

// Funct1();

//}

 

void Funct2(void)

{

try

{Funct1();}

catch(int)

{handler();}

}

 

// assume extern "C" functions don't throw exceptions

extern "C" void Funct4(void);

void Funct4(void)

{Funct1();}

 

int main(void)

{

Funct2();

try

{Funct4();}

catch(...)

{cout<<"Caught exception from Funct4()\n";}

Funct5();

return 0;

}

 

Output example:

 

Funct1() call #1

About to throw 1

In the handler()

Funct1() call #2

About to throw 1

Caught exception from Funct4()

Funct1() call #3

About to throw 1

In the handler()

Press any key to continue . . .

 

 

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