Wednesday 15 April 2009

A simple example of C++ Exceptions

Exceptions is a very powerful mechanism by which errors can be handled within the programs in C++. In C if an exception occurs (for example overflow, underflow, memory allocation failure, etc) then the program would just crash. In C++ these problems can be handled by use of exceptions.


//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
//This example shows different ways of throwing and catching
//exceptions and handling of exceptions

#include<iostream>
//#include<exception> //May be required on other platforms

using namespace
std;

void
function1();
void
function2();
void
function3();
void
function4();

class
zgException: public exception
{

//overloading the what() method
virtual const char* what() const throw()
{

return
"zgException occured";
}
}
zgEx;


int
main()
{

function1();
function2();
function3();
function4();

return
0;
}


//Throwing an integer
void function1()
{

cout<<"\nfunction1()"<<endl;
try

{

throw
123;
}

catch
(int a)
{

cout<<"Exception caught with value "<<a<<endl;
}
}


//Throwing a string but no mechanism to catch it
void function2()
{

cout<<"\nfunction2()"<<endl;
string s = "function2() exception";
try

{

throw
s;
}

catch
(exception &e)
{

cout<<"Exception message: "<<e.what()<<endl;
}

catch
(...)
{

cout<<"All exceptions not handled are caught here"<<endl;
}
}


//Throwing a string and catching it
void function3()
{

cout<<"\nfunction3()"<<endl;
string s = "function3() exception";
try

{

throw
s;
}

catch
(exception &e)
{

cout<<"Exception message: "<<e.what()<<endl;
}

catch
(string &ss)
{

cout<<"Exception message: "<<ss.c_str()<<endl;
}

catch
(...)
{

cout<<"All exceptions not handled are caught here"<<endl;
}
}


//Throwing a class and catching it
void function4()
{

cout<<"\nfunction4()"<<endl;
string s = "function4() exception";
try

{

throw
zgEx;
}

catch
(exception &e)
{

cout<<"Exception message: "<<e.what()<<endl;
}

catch
(...)
{

cout<<"All exceptions not handled are caught here"<<endl;
}
}






The output is as follows:

No comments:

Post a Comment