Sunday, June 03, 2007

Cpp Exceptions

Exceptions :
1.

The following code will catch the exception:

try
{
throw 100;
}
catch(int i)
{
printf(“\n Exception :%d”, i );
}


Exception :
Exception Testing () fn didn’t handle the exception then it will throws the exeption to the called function.


void ExceptionTesting()
{
throw 100;
}

int main(int argc, char* argv[])
{
try
{
ExceptionTesting();
}
catch(int i)
{
printf("\n main() fn exception : %d",i);

}
return 0;
}

Catching class types:
We can also create our own exceptions.

//Catching class type exceptions
#include
#include

class MyException
{
public:


MyException() { }

~MyException(){ }


};

int main(int argc, char* argv[])
{
int i = 0;

try
{
if(i == 0)
{
throw MyException();
}
}
catch(MyException e)
{
printf("\n Base classException");
}

return 0;
}
Catching Derived class Exception:

We can catch the derived class using the base class .

//Catching class type exceptions
#include
#include
class MyException
{
public:
MyException() { }
~MyException(){ }
};

class Derived:public MyException
{
public:
Derived(){ }
~Derived(){ }
};
int main(int argc, char* argv[])
{
int i = 0;

try
{
if(i == 0)
{
throw Derived();
}
}
catch(MyException e)
{
printf("\n Base classException");
}
catch(Derived d)
{
printf("\n Derived class Excption");
}

return 0;
}


Even though we passed the derived class exception, the base class will catch the “Base class Exception”.

Warning C4286: 'class Derived' : is caught by base class ('class MyException')

No comments: