//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